wpf - 如何将 xaml 中的绑定(bind)设置为我自己的变量

标签 wpf data-binding xaml

我在代码中有一个对象:

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

我需要将绑定(bind)设置为 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但仍然无法设置绑定(bind)。

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

最佳答案

您会收到 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"
}

关于wpf - 如何将 xaml 中的绑定(bind)设置为我自己的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2480013/

相关文章:

c# - 如何对可观察集合进行排序?

c# - 我应该对我的 Bootstrap 进行单元测试吗?如果是,如何进行?

javascript - 数据属性与 Knockout 的双向绑定(bind)

data-binding - VueJS : Updating a parent object won't be reflected on child

c# - WPF:实现 MediaPlayer 音频/视频搜索器

C# WPF 显示来自 Mysql 的图像

c# - 如何去除 ListBox 的模糊效果?

python - Python 中的数据绑定(bind)/数据转换

wpf - 使用 XAML 为 UserControl 中的所有元素添加前景色 setter

wpf - 与 TextBlock 具有相同剪辑的 TextBox(TextBox 模板)