WPF 属性数据绑定来否定属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2580467/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:38:58  来源:igfitidea点击:

WPF Property Data binding to negate the property

wpfdata-binding

提问by azamsharp

Is there any way to change the value of property at runtime in WPF data binding. Let's say my TextBox is bind to a IsAdmin property. Is there anyway I can change that property value in XAML to be !IsAdmin.

有什么方法可以在运行时更改 WPF 数据绑定中的属性值。假设我的 TextBox 绑定到 IsAdmin 属性。无论如何我可以将 XAML 中的该属性值更改为 !IsAdmin。

I just want to negate the property so Valueconverter might be an overkill!

我只是想否定这个属性,所以 Valueconverter 可能有点矫枉过正!

NOTE: Without using ValueConverter

注意:不使用 ValueConverter

回答by Reed Copsey

You can use an IValueConverter.

您可以使用一个IValueConverter.

[ValueConversion(typeof(bool), typeof(bool))]
public class InvertBooleanConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool original = (bool)value;
        return !original;
    }

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

Then you'd setup your binding like:

然后你会像这样设置你的绑定:

<TextBlock Text="{Binding Path=IsAdmin, Converter={StaticResource boolConvert}}" />

Add a resource (usually in your UserControl/Window) like so:

添加资源(通常在您的用户控件/窗口中),如下所示:

<local:InvertBooleanConverter  x:Key="boolConvert"/>


Edit in response to comment:

编辑以回应评论:

If you want to avoid a value converter for some reason (although I feel that it's the most appropriate place), you can do the conversion directly in your ViewModel. Just add a property like:

如果你出于某种原因想避免使用值转换器(虽然我觉得它是最合适的地方),你可以直接在你的 ViewModel 中进行转换。只需添加一个属性,如:

public bool IsRegularUser
{
     get { return !this.IsAdmin; }
}

If you do this, however, make sure your IsAdminproperty setter also raises a PropertyChangedevent for "IsRegularUser" as well as "IsAdmin", so the UI updates accordingly.

但是,如果您这样做,请确保您的IsAdmin属性设置器也PropertyChanged为“IsRegularUser”和“IsAdmin”引发事件,以便 UI 相应地更新。

回答by Jobi Joy

If you specifically want to do this at XAML end (I am not sure the reason for that, unless you have 100s of similar operation of negate) there are only two ways 1) Using IValueConverter 2)write a XAML Markup Extension (Way too much work for this small task :))

如果您特别想在 XAML 端执行此操作(我不确定原因,除非您有 100 次类似的否定操作),只有两种方法 1)使用 IValueConverter 2)编写 XAML 标记扩展(方式太多了)为这个小任务工作 :))

Then the other obvious way is to write another property in your ViewModel , which can return the Negative of the IsAdmin property.

然后另一个明显的方法是在您的 ViewModel 中编写另一个属性,它可以返回 IsAdmin 属性的 Negative 。

回答by Dan Bryant

You can't bind to !Property, but you could create a new Binding with an appropriate IValueConverter and change out the entire Binding at runtime. The key is the BindingOperations class, which allows you to change the binding on a particular DependencyProperty.

您不能绑定到 !Property,但您可以使用适当的 IValueConverter 创建一个新的 Binding 并在运行时更改整个 Binding。关键是 BindingOperations 类,它允许您更改特定 DependencyProperty 上的绑定。

    public static void InvertBinding(DependencyObject target, DependencyProperty dp)
    {
        //We'll invert the existing binding, so need to find it
        var binding = BindingOperations.GetBinding(target, dp);
        if (binding != null)
        {
            if (binding.Converter != null)
                throw new InvalidOperationException("This binding already has a converter and cannot be inverted");
            binding.Converter = new InvertingValueConverter(); //This would be your custom converter

            //Not sure if you need this step, but it will cause the binding to refresh
            BindingOperations.SetBinding(target, dp, binding);
        }
    }


This should give you a general idea; I wouldn't use this for production code, as you'd probably want to generalize it to toggle the converter or whatever else you need to change out at runtime. You could also avoid changing the binding entirely by creating a new property you bind to that encapsulates this 'switching' logic. The last option is probably the best.

这应该给你一个大致的概念;我不会将它用于生产代码,因为您可能希望将其概括为切换转换器或在运行时需要更改的任何其他内容。您还可以通过创建您绑定到的新属性来避免完全更改绑定,该属性封装了此“切换”逻辑。最后一个选项可能是最好的。

回答by Sascha

You can write a ValueConverter that automatically negates the inpurt before returning it. Have a look at BenCon's blogfor a short reading on value converters.

您可以编写一个 ValueConverter,在返回之前自动否定输入。查看BenCon 的博客,简要了解价值转换器。