WPF 属性数据绑定来否定属性 [英] WPF Property Data binding to negate the property

查看:24
本文介绍了WPF 属性数据绑定来否定属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

注意:不使用 ValueConverter

NOTE: Without using ValueConverter

推荐答案

您可以使用 IValueConverter.

You can use an 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:

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

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:

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

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

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

这篇关于WPF 属性数据绑定来否定属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆