【问题标题】:Binding button IsEnabled to a property将按钮 IsEnabled 绑定到属性
【发布时间】:2012-04-05 03:33:39
【问题描述】:

我有一个类实现了INotifyPropertyChanged。此类UserInfo 有一个布尔变量isuserLoggedIn。 现在在我的主窗体中,我希望将按钮的 isEnabled 绑定到 UserInfo.isuserLoggedIn

怎么做?

    public  class UserInfo : INotifyPropertyChanged
    {
        private static readonly UserInfo _instance = new UserInfo();
        private string username; 

        private  bool isLoggedIn;

        public string UserName
        {
            get { return username; }
            set
            {
                username = value;
                NotifyPropertyChanged("UserName");
            }
        }

        public  bool UserLoggedIn
        {
            get { return isLoggedIn; }
            set
            {
                isLoggedIn = value;
                NotifyPropertyChanged("UserLoggedIn");
            }
        }


        public  event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }               

    public static UserInfo GetUserInfo()
    {
        return _instance;
    }

}

我主要有:

public class MainWindow
{
    UserInfo currentUser = UserInfo.GetUserInfo();
}

XAML 是:

<Button IsEnabled="{Binding ElementName=currentUser, Path=UserLoggedIn}"/>

【问题讨论】:

    标签: wpf binding inotifypropertychanged isenabled


    【解决方案1】:

    您需要将视图的 DataContext 设置为 UserInfo 类的实例。然后将按钮的 IsEnabled 属性绑定到 UserInfo 视图模型上的 UserIsLoggedIn 布尔属性。下面是一个将元素的属性绑定到相应视图模型上的属性的示例:passing a gridview selected item value to a different ViewModel of different Usercontrol

    看到您的编辑后,您需要再次将视图的 DataContext 设置为 currentUser 对象,然后删除按钮的 IsEnabled 绑定表达式的 ElementName 部分。

    【讨论】:

    • 但是我已经在MainWindow UserInfo中声明了UserInfo类的一个实例 currentUser = UserInfo.GetUserInfo();并且 Button 的绑定如下: 为什么我还需要设置 DataContext?
    • 我认为您对 Silverlight 和 WPF 中数据绑定的工作方式有一点误解。您的绑定表达式将在视图的数据上下文中寻找匹配的属性。元素绑定是指将一个 XAML 元素的值绑定到另一个 XAML 元素的属性。
    【解决方案2】:

    您可以将IsEnabled绑定到用户名文本框的Length

    <TextBox Name="usernameTxt" Width="100" Height="30"/>
    <Button Content="SomeButton " Width="100" Height="30" 
      IsEnabled="{Binding ElementName=usernameTxt, Path=Text.Length, Mode=OneWay}"></Button>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-12
      • 2016-06-22
      • 1970-01-01
      相关资源
      最近更新 更多