此处给出的示例是我尝试实现的实际 UserControl 的简化,但它说明了结构并遇到了同样的问题。用户控件有一个 DependencyProperty Words,它设置在用户控件 XAML 中定义的文本块的文本。
public partial class MyControl : UserControl
{
public static readonly DependencyProperty WordsProperty = DependencyProperty.Register("Words", typeof(string), typeof(MyControl));
public MyControl()
{
InitializeComponent();
}
public string Words
{
get { return (string)GetValue(WordsProperty); }
set
{
m_TextBlock.Text = value;
SetValue(WordsProperty, value);
}
INotifyPropertyChanged ViewModelBase 类派生的 ViewModel 被分配给 mainWindow DataContext。ModelText 属性集调用 OnPropertyChanged。
class MainWindow : ViewModelBase
{
private string m_ModelString;
public string ModelText
{
get { return m_ModelString; }
set
{
m_ModelString = value;
base.OnPropertyChanged("ModelText");
}
}
}
在 MainWindow XAML 中绑定到 UserControl 和 TextBlock
<Window x:Class="Binding.View.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="218" Width="266" xmlns:my="clr-namespace:Binding.View">
<Grid>
<my:MyControl Words="{Binding ModelText}" HorizontalAlignment="Left" Margin="39,29,0,0" x:Name="myControl1" VerticalAlignment="Top" Height="69" Width="179" Background="#FF96FF96" />
<TextBlock Height="21" HorizontalAlignment="Left" Margin="59,116,0,0" Name="textBlock1" Text="{Binding ModelText}" VerticalAlignment="Top" Width="104" Background="Yellow" />
</Grid>
</Window>
绑定适用于文本块,但不适用于用户控件。为什么 UserControl DependencyProperty 不能和 Control Properties 一样绑定?