WPF数据绑定:根据var的内容启用/禁用控件?

Num*_*er8 12 c# data-binding wpf

我的表单上有一个按钮,只有在树视图(或tabitem中的列表视图)中选择项目时才能启用该按钮.选择项目时,它的值存储在字符串成员变量中.

我可以将IsEnabled按钮的属性绑定到成员var的内容吗?也就是说,如果成员var不为空,则启用该按钮.

类似地,当成员var的内容改变(设置或清除)时,按钮的状态应该改变.

apa*_*dit 12

由于您可能希望基于字符串绑定按钮的IsEnabled属性,请尝试为其创建转换器.

IE浏览器...


<StackPanel>
<StackPanel.Resources>
<local:SomeStringConverter mystringtoboolconverter />
</StackPanel.Resources>
<Button IsEnabled="{Binding ElementName=mytree, Path=SelectedItem.Header, Converter={StaticResource mystringtoboolconverter}}" />
<StackPanel>
Run Code Online (Sandbox Code Playgroud)

和转换器:


[ValueConversion(typeof(string), typeof(bool))]
    class SomeStringConverter : IValueConverter {
        public object Convert( object value, Type targetType, object parameter, CultureInfo culture ) {
            string myheader = (string)value;
            if(myhead == "something"){
                return true;
            } else {
                return false;
            }
        }

        public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture ) {
            return null;
        }
    }

编辑:由于OP想要绑定到变量,需要这样做:


public class SomeClass : INotifyPropertyChanged {
  private string _somestring;

  public string SomeString{
    get{return _somestring;}
    set{ _somestring = value; OnPropertyChanged("SomeString");}
  }

  public event PropertyChangedEventHandler PropertyChanged;
  protected void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

}

然后,将上面的绑定表达式更改为:

{Binding Path=SomeString, Converter={StaticResource mystringtoboolconverter}}

注意,您必须实现INotifyPropertyChanged才能更新UI.


And*_*rej 7

您是否有一个ViewModel将您的字符串属性设置为View的DataContext,您尝试在其中进行此绑定?

然后以下将工作:

  // Example ViewModel
public class MyClass : INotifyPropertyChanged
{
    private string text;

    public string Text
    {
        get { return text; }
        set 
        { 
            text = value;
            UpdateProperty("Text");
            UpdateProperty("HasContent");
        }
    }

    public bool HasContent
    {
        get { return !string.IsNullOrEmpty(text); }
    }


    public event PropertyChangedEventHandler PropertyChanged;

    protected void UpdateProperty(string name)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(name));
    }
}
Run Code Online (Sandbox Code Playgroud)

那么你应该在视图后面的代码中做过类似的事情:

this.DataContext = new MyClass();
Run Code Online (Sandbox Code Playgroud)

和一个Xaml示例:

 <StackPanel>
        <TextBox Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}" />
        <Button IsEnabled="{Binding HasContent}">
            Click Me!
        </Button>
    </StackPanel>
Run Code Online (Sandbox Code Playgroud)