【问题标题】:How to set binding in xaml to my own variable如何将 xaml 中的绑定设置为我自己的变量
【发布时间】:2010-03-19 19:20:01
【问题描述】:

我在代码中有一个对象:

public  class UserLogin
    {
        bool _IsUserLogin = false;

        public bool IsUserLogin
        {
            get { return _IsUserLogin; }
            set { _IsUserLogin = value; }
        }

        public UserLogin()
        {
            _IsUserLogin = false;
        }
    }
    ....
    public static UserLogin LoginState;
    .....
    LoginState = new UserLogin();

我需要将绑定设置为 Button.IsEnabled 属性。 IE。当用户尚未登录时 - 某些按钮被禁用。这是怎么做到的?我在 xaml 中尝试过:

<Button DataContext="LoginState" IsEnabled="{Binding Path=IsUserLogin}">

但是,这不起作用,OutputWindow 说:System.Windows.Data 错误:39:BindingExpression 路径错误:在“对象”上找不到“IsUserLogin”属性。 我也尝试在代码中将 Button.DataContext 属性设置为 LoginState,但有 XamlParseException。我也读过这个 [WPF - Binding in XAML to an object created in the code behind 但仍然无法设置绑定。

[1]:WPF - Binding in XAML to an object created in the code behind。请帮忙!

【问题讨论】:

    标签: wpf data-binding xaml


    【解决方案1】:

    您收到 XamlException 是因为编译器找不到名为“LoginState”的 (XAML)-Element。

    在程序代码中设置按钮的 DataContext。那么它应该可以工作了。

    public void SetDataContextOfButton() {
      UserLogin login = new UserLogin();
      button.DataContext = login; //Assumes that you name your Button in XAML with x:Name="button"
    }
    

    【讨论】:

    • 我是个白痴,我试图在 InitializeComponent(); 之前设置按钮的 DataContext;谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    相关资源
    最近更新 更多