[英]Set default value in XAML if binding is null
編輯
這不是字符串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所建議的,我已經實現了一個Converter:
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"/>
並將其添加到該屬性的綁定中:
但是僅在值不為null時才調用轉換器
我在另一個問題中找到了這個問題的答案(代碼來自Clemens):
<Window.Resources>
<model:PathSelector x:Key="FallbackPathSelector" />
</Window.Resources>
...
<ContentControl Content="{Binding MyPathSelector,
FallbackValue={StaticResource FallbackPathSelector}}"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.