我正在制作一个基本程序,当用户在文本框中输入内容时,标签会更新。我试图使用数据绑定和INotifyPropertyChanged解决这个问题,所以我不想要任何解决方法。我使用了2个按钮,所以我实际上可以看到他们是否更新。这里是我的主类无法从另一个类中的wpf获取标签
namespace TestStringChangeFromAnotherClass
public partial class MainWindow : Window
{
textClass someTextClass = new textClass();
public MainWindow()
{
InitializeComponent();
}
public string someString1;
public string someString2;
private void btn1_Click(object sender, RoutedEventArgs e)
{
someTextClass.Text1 = tbx1.Text;
}
private void btn2_Click(object sender, RoutedEventArgs e)
{
someTextClass.Text2 = tbx1.Text;
}
}
这里的WPF它
<Window x:Class="TestStringChangeFromAnotherClass.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button x:Name="btn1" Content="Button" HorizontalAlignment="Left" Height="36" Margin="29,246,0,0" VerticalAlignment="Top" Width="108" Click="btn1_Click"/>
<Button x:Name="btn2" Content="Button" HorizontalAlignment="Left" Height="36" Margin="227,246,0,0" VerticalAlignment="Top" Width="124" Click="btn2_Click"/>
<Label x:Name="lbl1" Content="{Binding textClass.Text1}" HorizontalAlignment="Left" Height="37" Margin="74,32,0,0" VerticalAlignment="Top" Width="153"/>
<Label x:Name="lbl2" Content="{Binding textClass.Text2, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Height="38" Margin="74,90,0,0" VerticalAlignment="Top" Width="153"/>
<TextBox x:Name="tbx1" HorizontalAlignment="Left" Height="37" Margin="290,32,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="190"/>
</Grid>
,你可以看到,我已经使用UpdateSourceTrigger尝试。我也尝试使用“someTestClass.Text1”而不是textClass.Test1,因为这就是我在MainWindow中定义它的方式。这里是我的textClass
namespace TestStringChangeFromAnotherClass
public class textClass:INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string text1;
public string Text1
{
get { return text1; }
set
{
text1 = value;
NotifyPropertyChanged("Text1");
}
}
private string text2;
public string Text2
{
get { return text2; }
set
{
text2 = value;
NotifyPropertyChanged("Text2");
}
}
protected void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
我无法弄清楚如何让WPF来寻找的Test1 Test2的或字符串在单独的类和更新他们当琴弦改变。我有一个感觉问题在于DataContext,但我无法弄清楚。我也宁愿不使用C#中的DataContext,只在WPF中
更新: 当我调试这个,当它到达NotifyPropertyChanged,PropertyChanged被评估为null。这可能是问题吗?
你有没有尝试在Mainwindow中实现INotifyPropertyChanged呢?因为这是你的数据上下文。 – TylerD87
如果我在MainWindow中添加INotifyPropertyChanged,我得到这个错误-'TestStringChangeFromAnotherClass。MainWindow'没有实现接口成员'System.ComponentModel.INotifyPropertyChanged.PropertyChanged' – darthwillard
也许,我需要做的是尝试让UpdateSourceTrigger查看TextClass类中的PropertyChanged项目? – darthwillard