码迷,mamicode.com
首页 > Windows程序 > 详细

C# Wpf双向绑定实例

时间:2016-08-12 16:37:22      阅读:296      评论:0      收藏:0      [点我收藏+]

标签:

Wpf中双向绑定处理需要两处

实例1:

1.前台Xaml中属性Binding 时Model指定 TwoWay

<Grid>
    <Ellipse  x:Name="ellipse"
        Fill="#FFF4F4F5" HorizontalAlignment="Left" 
                Height="{Binding Path=Number,Mode=TwoWay}" Margin="50,55,0,0" Stroke="Black"
                VerticalAlignment="Top" Width="{Binding Path=Number,Mode=TwoWay}"/>
    <Slider x:Name="slider"  Margin="28,167,22,0" ValueChanged="slider_ValueChanged"
            VerticalAlignment="Top" TickPlacement="Both" Maximum="100" SmallChange="1"/>
    <Label x:Name="label" Content="{Binding Path=Number,Mode=TwoWay}" HorizontalAlignment="Left" Margin="110,150,0,0" VerticalAlignment="Top"/>
</Grid>

2.后台绑定的数据上线文实现INotifyPropertyChanged(向客户端发出某一属性值已更改的通知。)接口

/// <summary>
/// Thread6.xaml 的交互逻辑
/// </summary>
public partial class Thread6 : Window
{

    TestData testData = new TestData() { Number = 10 };
    public Thread6()
    {
        InitializeComponent();
        //创建双向绑定
        ellipse.DataContext = testData;
        label.DataContext = testData;
    }
    private void slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
    {
        testData.Number = (int)e.NewValue;
    }
}
public class TestData : INotifyPropertyChanged
{
    private int _Number;
    public int Number
    {
        get
        {
            return _Number;
        }
        set
        {
            _Number = value;
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Number"));
            }
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

显示结果:

技术分享

实例2:使用Wpf的双向绑定机制,可以实现多线程修改UI

注:其他线程修改绑定数据时会通知到UI线程修改界面数据。

TestData类定义同上

Xaml定义同上

//创建双向绑定
ellipse.DataContext = testData;
//创建线程修改数据
Task.Run(() =>
{
    while (true)
    {
        testData.Number++;
        if (testData.Number == 200)
            testData.Number = 0;
        Thread.Sleep(100);
    }
});

技术分享

C# Wpf双向绑定实例

标签:

原文地址:http://www.cnblogs.com/tianma3798/p/5765464.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!