我正在努力解決一些綁定問題。 我有一個用戶控件與TextBlock。 TextBlock的文本綁定到一個屬性。 在窗口中使用UserControl並使用某些文本設置屬性時,一切都按預期工作。但是當我將該屬性綁定到窗口中的另一個屬性時,什麼都不會發生。 這是一個例子,顯示了問題:將UserControl屬性綁定到Window屬性
用戶控件XAML:
<UserControl x:Class="TestBinding.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<TextBlock Text="{Binding SomeText}"/>
用戶控件代碼:
public partial class UserControl1 : UserControl
{
public static readonly DependencyProperty SomeTextProperty = DependencyProperty.Register("SomeText", typeof(string), typeof(UserControl1), new PropertyMetadata("Control Default Text"));
public string SomeText
{
get { return (string)this.GetValue(SomeTextProperty); }
set { this.SetValue(SomeTextProperty, value); }
}
public UserControl1()
{
this.DataContext = this;
InitializeComponent();
}
}
窗口XAML:
<Window x:Class="TestBinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestBinding"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="1*"/>
<RowDefinition Height="1*"/>
</Grid.RowDefinitions>
<local:UserControl1 Grid.Row="0" Grid.Column="0"/>
<local:UserControl1 Grid.Row="1" Grid.Column="0" SomeText="Another Text" />
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding SomeText}"/>
<local:UserControl1 Grid.Row="1" Grid.Column="1" SomeText="{Binding SomeText}" />
</Grid>
窗口代碼:
public partial class MainWindow : Window
{
public static readonly DependencyProperty SomeTextProperty = DependencyProperty.Register("SomeText", typeof(string), typeof(MainWindow), new PropertyMetadata("Window Default Text"));
public string SomeText
{
get { return (string)this.GetValue(SomeTextProperty); }
set { this.SetValue(SomeTextProperty, value); }
}
public MainWindow()
{
this.DataContext = this;
InitializeComponent();
}
}
我期望在右下角看到的是「窗口默認文本」但我得到的是「控制默認文本」。
感謝您的幫助