您的位置:首页 > 其它

WPF Grid 数据绑定,当数据源发生变化后控件值随之更新

2013-03-21 14:38 537 查看
前台页面:

<Window x:Class="WPFTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Grid  Name="gdTest">
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
</Grid.RowDefinitions>

<StackPanel  Grid.Row="0" Orientation="Horizontal" >
<TextBlock  Width="80" TextAlignment="Right" VerticalAlignment="Center" >测试1:</TextBlock>
<TextBox Width="100" VerticalAlignment="Center"  Text="{Binding Path=Test1}" Name="txtTest1" ></TextBox>

</StackPanel>
<StackPanel  Grid.Row="1" Orientation="Horizontal" >
<TextBlock  Width="80" TextAlignment="Right" VerticalAlignment="Center" >测试2:</TextBlock>
<TextBox Width="100" VerticalAlignment="Center"  Text="{Binding Path=Test2}" Name="txtTest2"  ></TextBox>
</StackPanel>

<StackPanel  Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Right" >
<Button Height="30" Width="80" Name="btnTest" Click="btnTest_Click" Margin="0,0,5,0" >确定</Button>
</StackPanel>
</Grid>
</Window>


后台代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WPFTest
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();

}
public Tset test = new Tset();
private void btnTest_Click(object sender, RoutedEventArgs e)
{
test.Test1 = "111111";
test.Test2 = "222222";
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
gdTest.DataContext = test;
}
}
}


绑定的实体类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace WPFTest
{
public class Tset : INotifyPropertyChanged
{

[field: NonSerializedAttribute()]
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
private string _test1;
public string Test1
{
get
{
return _test1;
}
set
{
if (_test1 != value)
{
_test1 = value;
NotifyPropertyChanged("Test1");
}
}
}
public string Test2 { get; set; }
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: