如果绑定为空,则在 XAML 中设置默认值
Set default value in XAML if binding is null
编辑
这不是字符串空值回退的重复。我要求一个复杂类型的回退。
原题
这是我昨天提出的问题的后续问题:
我接受的答案的核心部分是:
<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();
}
}
我在我的 window:
中添加了一个转换器实例资源
<view:PathSelectorConverter x:Key="pathSelectorConverter"/>
并将其添加到 属性 的绑定中:
但只有当值不为空时才会调用转换器
我在我的另一个 中找到了这个问题的答案(代码来自 Clemens):
<Window.Resources>
<model:PathSelector x:Key="FallbackPathSelector" />
</Window.Resources>
...
<ContentControl Content="{Binding MyPathSelector,
FallbackValue={StaticResource FallbackPathSelector}}"/>
编辑
这不是字符串空值回退的重复。我要求一个复杂类型的回退。
原题
这是我昨天提出的问题的后续问题:
我接受的答案的核心部分是:
<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();
}
}
我在我的 window:
中添加了一个转换器实例资源<view:PathSelectorConverter x:Key="pathSelectorConverter"/>
并将其添加到 属性 的绑定中:
但只有当值不为空时才会调用转换器
我在我的另一个
<Window.Resources>
<model:PathSelector x:Key="FallbackPathSelector" />
</Window.Resources>
...
<ContentControl Content="{Binding MyPathSelector,
FallbackValue={StaticResource FallbackPathSelector}}"/>