如何在XAML中将绑定设置为自己的变量

3

我在代码中有一个对象:

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();

我需要设置按钮的绑定属性IsEnabled。例如,当用户尚未登录时,禁用某些按钮。这该如何实现?我已经在XAML中尝试过以下代码:
<Button DataContext="LoginState" IsEnabled="{Binding Path=IsUserLogin}">

但是,这并不起作用,OutputWindow显示:System.Windows.Data Error: 39 : BindingExpression路径错误:'IsUserLogin'属性在'object'上未找到。 我还尝试将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。请帮忙!
1个回答

1

你会收到XamlException异常,因为编译器找不到名为“LoginState”的(XAML)元素。

在程序代码中设置按钮的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。谢谢! - Victor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接