[英]WPF Binding Converter does not run when Property Path is null
I have this class: 我有这个课:
public class MyClass
{
public bool? Accepted { get; set; } = true;
}
... and this ViewModel: ...以及此ViewModel:
public class MyViewModel
{
public MyClass MyClass => null;
}
... and this View: ...以及此视图:
<MyControl.Resources>
<mynamespace:RedColorWhenNullConverter x:Key="RedColorWhenNullConverter" />
</MyControl.Resources>
<Rectangle
Height="100"
Width="100"
Fill="{Binding MyClass.Accepted, Converter={StaticResource RedColorWhenNullConverter}}"
/>
... and this ValueConverter: ...以及此ValueConverter:
public class RedColorWhenNullConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value == null ? new SolidColorBrush(Colors.Red) : new SolidColorBrush(Colors.Green);
}
{...}
}
When the view model returns null for MyClass
property, the converter does not run at all. 当视图模型为
MyClass
属性返回null时,转换器将完全不运行。 I was expecting it to run with the value null
. 我期望它以
null
值运行。
If the DataContext
of the view is MyClass
and the binding was directly to the Accepted
property like this: {Binding Accpected, ...
, and Accepted
property returns null
the converter runs. 如果视图的
DataContext
是MyClass
并且绑定是直接这样的到Accepted
属性: {Binding Accpected, ...
,并且Accepted
属性返回null
则转换器运行。
How is this any different from the binding chain MyClass.Accepted
? 这与绑定链
MyClass.Accepted
什么不同? And is there any workarounds for this issue? 有没有解决此问题的方法?
Does there exist a null-conditional operator for xaml as in C#
? 是否像
C#
那样存在xaml的空条件运算符? Would be nice to do this {Binding MyClass?.Accepted, ...
. 做到这一点
{Binding MyClass?.Accepted, ...
The Binding Converter is supposed to convert the value of the Binding's source property to a value that is assignable to the target property. 绑定转换器应该将绑定的source属性的值转换为可分配给target属性的值。
If the value of the source property can not be evaluated, the Converter can't be called. 如果无法评估source属性的值,则无法调用Converter。
You may add FallbackValue=Red
to the Binding, but the Converter is still not called. 您可以将
FallbackValue=Red
添加到绑定中,但是仍然不调用Converter。
Alternatively do not use a Converter at all, but a Style with DataTriggers and a default value for the Fill
property: 或者,根本不使用Converter,而是使用具有DataTriggers的Style和
Fill
属性的默认值:
<Rectangle Height="100" Width="100">
<Rectangle.Style>
<Style TargetType="Rectangle">
<Setter Property="Fill" Value="Red"/>
<Style.Triggers>
<DataTrigger Binding="{Binding MyClass.Accepted}" Value="False">
<Setter Property="Fill" Value="Blue"/>
</DataTrigger>
<DataTrigger Binding="{Binding MyClass.Accepted}" Value="True">
<Setter Property="Fill" Value="Green"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Rectangle.Style>
</Rectangle>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.