我想将标签的内容绑定到名为“Status”的本地属性。
Codesnipped:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var logFilePath = GetPathToAppDirPlusLocalPath("LogFiles/MainLog.txt");
MainLog = new Log(@logFilePath);
MainLog.Add("MainWindow initialized");
this.DataContext = this;
}
private string _Status = null;
public string Status
{
get
{
return _Status;
}
set
{
_Status = value;
NotifyPropertyChanged("Status"); //Call the method to set off the PropertyChanged event.
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void NotifyPropertyChanged(string propertyName = "")
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
XAML:
<Border x:Name="brd_Status" Grid.Row="9" Grid.ColumnSpan="10"
HorizontalAlignment="Stretch" VerticalAlignment="Bottom"
Background="Black" DataContext="Status">
<Label x:Name="lbl_Status" Content="{Binding Path=Status,UpdateSourceTrigger=PropertyChanged}"
Grid.Row="9" Grid.ColumnSpan="10"
HorizontalAlignment="Center" VerticalAlignment="Bottom"
FontSize="16" Foreground="White" FontFamily="Asenine">
</Label>
</Border>
我也试过Content = {Binding Status...}
,但没有任何区别。
标签只是“null”,而属性“Status”是“abcd1234 ......”。
我调试了它,但是,我不知道在哪里搜索失败......
答案 0 :(得分:1)
问题是MainWindow
没有实现INotifyPropertyChanged
,所以即使您已经并且正在提出相应的事件,运行时也没有注册它。
将班级定义更改为:
public partial class MainWindow : Window, INotifyPropertyChanged
还考虑使用正确的视图模型(查找MVVM),将INPC置于视图对象上是非常糟糕的设计,并注意UpdateSourceTrigger
上的Label
由于无法在UI中更改Label
控件,因此无效。