问题描述
在WPF数据绑定中有什么办法可以改变运行时的属性值。假设我的TextBox绑定到IsAdmin属性。有没有办法我可以改变XAML中的属性值是!IsAdmin。我只是想否定属性,所以Valueconverter可能是一个过分的! b
$ b
注意:不使用ValueConverter
您可以使用。
[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;
}
}
然后,您将设置如下绑定: p>
< TextBlock Text ={Binding Path = IsAdmin,Converter = {StaticResource boolConvert}}/>
添加资源(通常在您的UserControl / Window中),如下所示:
< local:InvertBooleanConverter x:Key =boolConvert/>
编辑响应评论:
如果你想避免某种原因的值转换器(虽然我觉得这是最合适的地方),你可以直接在ViewModel中进行转换。只需添加一个属性:
public bool IsRegularUser
{
get {return!this.IsAdmin; }
}
但是,如果这样做,请确保您的 IsAdmin
属性setter还为IsRegularUser以及IsAdmin引发了一个 PropertyChanged
事件,所以UI会相应地更新。
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.
I just want to negate the property so Valueconverter might be an overkill!
NOTE: Without using ValueConverter
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:
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; }
}
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属性数据绑定以取消属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!