Jer*_*xon 6 data-binding wpf xaml coalesce targetnullvalue
在SQL中我可以这样做:
Select Coalesce(Property1, Property2, Property3, 'All Null') as Value
From MyTable
Run Code Online (Sandbox Code Playgroud)
如果Property1,2和3都为null,那么我得到'All Null'
我如何在XAML中执行此操作?我试过以下,但没有运气:
<Window.Resources>
<local:Item x:Key="MyData"
Property1="{x:Null}"
Property2="{x:Null}"
Property3="Hello World" />
</Window.Resources>
<TextBlock DataContext="{StaticResource MyData}">
<TextBlock.Text>
<PriorityBinding TargetNullValue="All Null">
<Binding Path="Property1" />
<Binding Path="Property2" />
<Binding Path="Property3" />
</PriorityBinding>
</TextBlock.Text>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)
结果应该是'Hello World',而是'All Null'
我希望我的问题很明确.
Cod*_*ked 10
您必须构建一个自定义IMultiValueConverter才能执行此操作并使用MultiBinding.PriorityBinding使用集合中的第一个绑定成功生成值.在您的情况下,Property1绑定立即解析,因此使用它.由于Property1为null,因此使用TargetNullValue.
像这样的转换器:
public class CoalesceConverter : System.Windows.Data.IMultiValueConverter
{
public object Convert(object[] values, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
if (values == null)
return null;
foreach (var item in values)
if (item != null)
return item;
return null;
}
public object[] ConvertBack(object value, Type[] targetTypes,
object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
Run Code Online (Sandbox Code Playgroud)
和MultiBinding像这样:
<Window.Resources>
<local:Item x:Key="MyData"
Property1="{x:Null}"
Property2="{x:Null}"
Property3="Hello World" />
<local:CoalesceConverter x:Key="MyConverter" />
</Window.Resources>
<TextBlock DataContext="{StaticResource MyData}">
<TextBlock.Text>
<MultiBinding Converter="{StaticResource MyConverter}">
<Binding Path="Property1" />
<Binding Path="Property2" />
<Binding Path="Property3" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1071 次 |
| 最近记录: |