我有一个场景,我希望在字符串属性发生变化时将字符串属性绑定到UI上的文本框。我想在后面的代码中更改属性。请在下面找到我的工作:
XAML :
<Window x:Class="databinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:test="clr-namespace:databinding"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox Text="{Binding mobile1}" Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" />
<TextBox Text="{Binding mobile2}" Height="23" HorizontalAlignment="Left" Margin="10,43,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" />
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="10,76,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
</Grid>
请在下面找到MainWindow.xaml.cs:
namespace databinding
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
void button1_Click(object sender, RoutedEventArgs e)
{
talk ta = new talk();
ta.test();
}
}
}
请找到我定义我的属性的类:
mobile.cs:
namespace databinding
{
public class mobile:INotifyPropertyChanged
{
string mobile1model;
string mobile2model;
public string mobile1 { get { return mobile1model; } set { mobile1model = value; OnPropertyChanged(new PropertyChangedEventArgs("mobile1")); } }
public string mobile2 { get { return mobile2model; } set { mobile2model = value; OnPropertyChanged(new PropertyChangedEventArgs("mobile2")); } }
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
{
PropertyChanged(this, e);
}
}
}
}
现在我有一个测试类,我在其中更改了属性值:
test.cs:
namespace databinding
{
public class talk:MainWindow
{
public void test()
{
mobile mb = new mobile();
mb.mobile1 = "This is mobile 1";
mb.mobile2 = "This is mobile 2";
}
}
}
这里的问题陈述是,当我点击button1时,属性会更新,但UI上的文本框不会更新,我也在查看文本框是否在属性更改时更新或是否等待直到第二个属性更改才能更新?感谢您对此查询的支持。
提前致谢。
答案 0 :(得分:3)
创建mobile
类的一个实例,将其设置为Window.DataContext
并在该实例上调用test()
public partial class MainWindow : Window
{
private readonly mobile _mb = new mobile();
public MainWindow()
{
InitializeComponent();
DataContext = _mb;
}
public void test()
{
_mb.mobile1 = "This is mobile 1";
_mb.mobile2 = "This is mobile 2";
}
void button1_Click(object sender, RoutedEventArgs e)
{
this.test();
}
}