XAML绑定到财产 [英] XAML Binding to property

查看:116
本文介绍了XAML绑定到财产的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的XAML + C#的Windows Store应用程序复选框。我也有布尔属性: WindowsStoreTestApp.SessionData.RememberUser 这是公共的和静态

I have check box in my XAML+C# Windows Store application. Also I have bool property: WindowsStoreTestApp.SessionData.RememberUser which is public and static.

我要复选框的财产。 器isChecked 是一致的(或绑定,或映射)到这个布尔属性。

I want check box's property IsChecked to be consistent (or binded, or mapped) to this bool property.

我试过这样:
XAML

I tried this: XAML

<CheckBox x:Name="chbRemember1"  IsChecked="{Binding Mode=TwoWay}"/>



C#

C#

chbRemember1.DataContext = SessionData.RememberUser;



代码属性:

Code for property:

namespace WindowsStoreTestApp
{
    public class SessionData
    {
        public static bool RememberUser { get; set; }
    }
}



但它似乎并没有工作。你能帮助我吗?

But it doesn't seem to work. Can you help me?

推荐答案

您需要实施某种形式的变更通知,以便您的复选框是感知任何更改属性。最好的办法是使用许多MVVM框架之一在那里,如果没有,实施 INotifyPropertyChanged的在你的视图模型。

You need to implement some form of change notification in order for your check box to be "aware" of any changes to the property. The best bet is to use one of the many MVVM frameworks out there, if not, implement INotifyPropertyChanged in your ViewModel.

另外,通常在WPF中,我们不设置各个控件的DataContext的,但窗口或用户控件的DataContext的设置为一个ViewModel ...

Also, typically in WPF, we do not set the DataContext of individual controls but set the DataContext of the Window or User Control to a ViewModel...

下面是通过MVVM框架之一,更改通知的属性的例子:

Here is an example of a property with change notification through one of the MVVM frameworks:

private bool createTrigger;
public bool CreateTrigger
{
    get { return createTrigger; }
    set { createTrigger = value; NotifyPropertyChanged(m => m.CreateTrigger); }
}



正如你可以看到一个简单的自动实现的属性不能用于数据在WPF结合...

As you can see a simple auto-implemented property cannot be used for data binding in WPF...

我建议通过的数据绑定概述MSDN上的过...

I'd recommend going through Data Binding Overview over on MSDN...

这篇关于XAML绑定到财产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆