这里给出的示例是我试图实现的实际UserControl的简化,但它说明了结构并遭受同样的问题。用户控件具有一个DependencyProperty Words,用于设置在用户控件XAML中定义的文本块的文本。衍生视图模型将UserControl属性绑定到INotifyPropertyChanged视图模型
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类被分配给主窗口的DataContext。 ModelText属性集调用OnPropertyChanged。
class MainWindow : ViewModelBase
{
private string m_ModelString;
public string ModelText
{
get { return m_ModelString; }
set
{
m_ModelString = value;
base.OnPropertyChanged("ModelText");
}
}
}
在主窗口XAML绑定到用户控件和一个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?
您需要格式化与{} – Paparazzi
的代码块我也尝试使用{}但很明显,我没有错。对不起,这是我第一次尝试。 – user1683083