【问题标题】:Set default value in XAML if binding is null如果绑定为空,则在 XAML 中设置默认值
【发布时间】:2017-12-03 03:11:34
【问题描述】:

编辑

这与字符串空值的回退没有重复。我要求一个复杂类型的后备。

原始问题

这是我昨天提出的问题的后续问题:

Bind WPF Command to ViewModel property in C# XAML

我接受的答案的核心部分是:

<Window.Resources>
    <DataTemplate DataType="{x:Type local:SettingsPathSelectorViewModel}">
        <StackPanel Orientation="Horizontal">
            <TextBox Text="{Binding SettingsPath}" />
            <Button 
                Content="..." 
                Command="{Binding OpenFile}" 
                HorizontalAlignment="Left" 
                MinWidth="40" 
                Margin="4,0,0,0" 
                />
        </StackPanel>
    </DataTemplate>
</Window.Resources>
<Grid>
    <StackPanel Orientation="Vertical">
        <Label>First Path</Label>
        <ContentControl Content="{Binding FirstPath}" />
    </StackPanel>
</Grid>

为自定义类型创建 DataTemplate,然后将 ContentControl 绑定到该类型的属性。

现在的问题是,属性(示例中为FirstPath)可能是null,并且没有呈现任何UI 元素。即使属性是null,我如何才能从DataTemplate 呈现控件

正如 Evk 建议的那样,我已经实现了一个转换器:

public class PathSelectorConverter : IValueConverter
{
    public object Convert(object o, Type type, object parameter, CultureInfo culture)
    {
        return o ?? new PathSelector();
    }
    public object ConvertBack(object o, Type type, object parameter, CultureInfo culture)
    {
        return o ?? new PathSelector();
    }
}

我在我的窗口中添加了一个资源转换器的实例:

<view:PathSelectorConverter x:Key="pathSelectorConverter"/>

并将其添加到属性的绑定中:

但只有当值不为空时才会调用转换器

【问题讨论】:

  • 你不能确保它永远不会为空吗?
  • @Evk 不幸的是没有。我有一个您可以从中选择的元素列表,每个元素都有一个 FirstPath 属性。如果元素列表为空,我会出现这种不良行为。
  • 然后你可以使用一个转换器,如果提供的值为 null,它将返回 SettingsPathSelectorViewModel 的一些默认实例。
  • @Evk 你有这样一个转换器描述的链接吗?
  • 如果使用TargetNullValue的绑定呢?

标签: c# wpf xaml data-binding datatemplate


【解决方案1】:

我在我的另一个question 中找到了这个问题的答案(代码来自 Clemens):

<Window.Resources>
    <model:PathSelector x:Key="FallbackPathSelector" />
</Window.Resources>
...

<ContentControl Content="{Binding MyPathSelector,
                          FallbackValue={StaticResource FallbackPathSelector}}"/>

【讨论】:

    猜你喜欢
    • 2015-02-13
    • 2013-03-23
    • 2016-01-02
    • 1970-01-01
    • 2017-12-05
    • 2017-05-15
    • 2013-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多