我正在尝试使用 PropertyChangedEventHandler
更新属性,但我认为我对其工作原理的概念性理解可能有点缺陷。因为我是 WPF 和 silver-light 的新手。
所以,让我解释一下,我有一个设置为 0 的属性,但是一段时间后线程在内部将值从 0 更改为 9,但是尽管值发生了变化,但该属性在实际 View 中永远不会更新我不知道为什么!即使在我实现了 PropertyChangedEventHandler
之后也没有任何变化,但是如果我记录该属性,它会显示该值实际上是 9
下面是实现 PropertyChangedEventHandler
的代码片段:
public class CustomColumn : IColumnViewable, INotifyPropertyChanged
{
...
public event PropertyChangedEventHandler PropertyChanged = delegate { };
public void OnPropertyChanged(string propertyName)
{
Foo.log.Error(": start on property change");
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
Foo.log.Error(": end on property change");
}
public static string _total;
public string total { get { return _total; } set { _total = value; OnPropertyChanged("total"); Foo.log.Error(": property change"); } }
...
}
这是我的 xaml 的一部分:
<DataTemplate x:Key="ColumnView">
<UserControl HorizontalAlignment="Stretch">
<StackPanel HorizontalAlignment="Stretch">
...
<RichTextBox Margin="5,2,5,2">
<Paragraph>
<Run Text="{Binding Path=total, Mode=OneWay}" FontWeight="Bold" FontSize="30" />
<Run Text=" total clicks" FontWeight="Bold" />
</Paragraph>
</RichTextBox>
...
<ContentControl VerticalAlignment="Stretch" Content="{Binding Path=timeline}" ContentTemplate="{Binding Path=timelineView.ContentTemplate}" />
</StackPanel>
</UserControl>
</DataTemplate>
我在初始化时这样做:
CustomColumn content = new CustomColumn();
content.total = "0";
然后我将对象传递给一个线程,该线程有时会这样做:
content.total = "9";
Foo.log.Error("value is "+content.total);
而且属性从不更新,我不知道为什么 - 非常感谢任何帮助
最佳答案
如果我了解您问题的详细信息,则说明您正在后台线程上更新 UI 绑定(bind)值。您需要在 UI 线程上实现这一点,否则更改将不可见。在我们意识到这一点之前,在我们的一个 WPF 应用程序中随机更新消失了。
我们在我们的 Silverlight(和 WPF)应用程序中做了很多多线程,为了避免这个问题,我们在一个基类中实现了我们的通知助手,如下所示(其他内容被删减)。它在主 UI 线程上调度所有通知消息。试一试:
public class ViewModelBase : INotifyPropertyChanged
{
protected delegate void OnUiThreadDelegate();
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
// Ensure property change is on the UI thread
this.OnUiThread(() => this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)));
}
}
protected void OnUiThread(OnUiThreadDelegate onUiThreadDelegate)
{
// Are we on the Dispatcher thread ?
if (Deployment.Current.Dispatcher.CheckAccess())
{
onUiThreadDelegate();
}
else
{
// We are not on the UI Dispatcher thread so invoke the call on it.
Deployment.Current.Dispatcher.BeginInvoke(onUiThreadDelegate);
}
}
}
关于c# - 更新 silverlight 中的属性绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6472055/