【发布时间】:2018-03-13 17:28:15
【问题描述】:
我已经玩了一段时间,并决定看看是否有人可以提供帮助,我在 StatusInfo 的构造函数中设置了 DataContext = this 并且没有工作。当我将字符串写入 ScreenStatusBarText 时,它确实调用了 OnPropertyChanged 方法,但每次 PropertyChanged 值为空。我在屏幕底部的状态块。我在此堆栈面板上方有一个选项卡部分,其中包含许多使用绑定和工作的组件。
屏幕代码
<StackPanel Margin="0,1047,0,0">
<Grid Name="StatusBarItemGrid">
<TextBlock Name="StatusBarText" Text="may the force be with you" VerticalAlignment="Center" HorizontalAlignment="Stretch" />
</Grid>
</StackPanel>
数据模型:
public partial class StatusInfo : INotifyPropertyChanged
{
private string screenStatusBarText;
public StatusInfo()
{
BindScreenStatusBarText();
screenStatusBarText = "Initialized";
}
public string ScreenStatusBarText
{
get { return screenStatusBarText; }
set
{
screenStatusBarText = value;
OnPropertyChanged("StatusBarText");
}
}
private void BindScreenStatusBarText()
{
Binding b = new Binding();
b.Source = screenStatusBarText;
b.Mode = BindingMode.OneWay;
b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
b.Path = new PropertyPath("StatusBarText");
MainWindow.mainWindow.StatusBarText.SetBinding(TextBlock.TextProperty, b);
MainWindow.mainWindow.StatusBarText.DataContext = this;
}
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string propName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(
this, new PropertyChangedEventArgs(propName));
}
}
我的主要:
public partial class MainWindow : Window
{
public static StatusInfo status;
public MainWindow()
{
InitializeComponent();
SourceInitialized += MainWindow_SourceInitialized;
}
private void MainWindow_SourceInitialized(object sender, EventArgs e)
{
SetUpDisplay();
}
private void SetUpDisplay()
{
status = new StatusInfo();
}
}
【问题讨论】:
-
你能改写吗我在StatusInfo的构造函数中设置了DataContext = this并且没有工作。我不清楚
-
为什么不在 XAML 中建立绑定?您的方法看起来,嗯,倒退...也就是说,乍一看,我发现您没有正确使用 Binding.Source 属性。请参阅其文档 (msdn.microsoft.com/en-us/library/…) 以了解此属性的用途。此外,绑定的 PropertyPath 并不真正匹配任何东西。如果您想坚持在代码隐藏中构建/创建绑定,则需要格外注意。
-
我没看到你在哪里设置 DataContext ?
-
WPF/UWP 和 XAML 在设计时考虑了 MVVM 模式。这看起来不像 MVVM 模式。虽然您可以使用其他方法,但这样做会丢失大约 90% 的功能,并且在其他任何地方都会遇到问题。多年前我写了一篇关于 MVVM 的简短介绍:social.msdn.microsoft.com/Forums/vstudio/en-US/… |希望切换到它对您有所帮助。
-
旁注:在你的二传手中,你可能想先做:
if (value == screenStatusBarText) return;
标签: c# wpf data-binding inotifypropertychanged textblock