【发布时间】:2013-09-13 06:01:59
【问题描述】:
我最近对Binding Mode = OneWayToSource 进行了大量测试,但我仍然不知道为什么会发生某些事情。
例如,我在类构造函数中的 dependency property 上设置了一个值。现在,当 Binding 初始化时,Target 属性被设置为其默认值。意味着 dependency property 被设置为 null 并且我失去了在 constructor 中初始化的值。
为什么会这样? Binding Mode 没有按照名称描述的方式工作。它应该只更新Source 而不是Target
代码如下:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new MyViewModel();
}
private void OnClick(object sender, RoutedEventArgs e)
{
this.DataContext = new MyViewModel();
}
}
这是 XAML:
<StackPanel>
<local:MyCustomControl Txt="{Binding Str, Mode=OneWayToSource}"/>
<Button Click="OnClick"/>
</StackPanel>
这是 MyCustomControl:
public class MyCustomControl : Control
{
public static readonly DependencyProperty TxtProperty =
DependencyProperty.Register("Txt", typeof(string), typeof(MyCustomControl), new UIPropertyMetadata(null));
static MyCustomControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new FrameworkPropertyMetadata(typeof(MyCustomControl)));
}
public MyCustomControl()
{
this.Txt = "123";
}
public string Txt
{
get { return (string)this.GetValue(TxtProperty); }
set { this.SetValue(TxtProperty, value); }
}
}
这是 ViewModel:
public class MyViewModel : INotifyPropertyChanged
{
private string str;
public string Str
{
get { return this.str; }
set
{
if (this.str != value)
{
this.str = value; this.OnPropertyChanged("Str");
}
}
}
protected void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null && propertyName != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
【问题讨论】:
-
你能显示一些代码吗,因为我无法复制你所描述的内容
-
你没有得到哪一部分?
-
我都得到了,只是无法复制。
-
有代码。试试看。
-
您是否尝试在 ViewModel 中设置
private string str = "123"?