简体   繁体   English

WPF MVVM依赖项属性获取负值

[英]WPF MVVM dependency Property Get negative value

I have two buttons, SEND and UNSEND. 我有两个按钮,SEND和UNSEND。 I want to enable or disable the buttons using the boolean IsSended . 我想使用boolean IsSended启用或禁用按钮。

I've created a dependency property which can be used to enable one of the buttons, but how I can take the negative value to control the other button? 我已经创建了一个依赖属性,该属性可用于启用一个按钮,但是如何使用负值来控制另一个按钮呢?

VIEW 视图

dxb:BarButtonItem Content="SEND" IsEnabled="{Binding !IsSent}" 
dxb:BarButtonItem Content="UNSEND" IsEnabled="{Binding IsSent}" 

VIEWMODEL 视图模型

public Boolean IsSent
{
   get { return (Boolean) GetValue(IsSendedProperty); }
   set { SetValue(IsSendedProperty, value); }
}

public static readonly DependencyProperty IsSendedProperty = DependencyProperty.Register("IsSent", typeof(Boolean), typeof(ViewModel), new PropertyMetadata(default(Boolean)));

There are a number of was to do this in WPF; WPF中有很多这样做的目的。 IValueConverters , DataTemplate or overriding the ControlTemplate . IValueConvertersDataTemplate或覆盖ControlTemplate

It is hard to know which would be the best in the long run for your particular application, but the simplest to show here is the IValueConverter . 从长远来看,对于您的特定应用程序,哪一个是最好的,这是很难知道的,但是在这里显示的最简单的是IValueConverter

Add a class called, for example, NegateBoolConverter 添加一个名为NegateBoolConverter

public class NegateBoolConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return !(bool)value;
    }


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

Create an instance of this class in XAML (I put all my converters all the way up in the App.xaml , but you could put it in the <Window.Resources> section. 在XAML中创建此类的实例(我将所有转换器都放在App.xaml ,但是您可以将其放在<Window.Resources>部分中。

  <Window.Resources>
    <local:NegateBoolConverter x:Key="MyConverter"/>
  </Window.Resources>

where local: is a namespace to the converter class 其中local:是转换器类的名称空间

Then your binding becomes: 然后,您的绑定变为:

  <dxb:BarButtonItem Content="SEND" IsEnabled="{Binding IsSended, Converter={StaticResource MyConverter}}">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM