[英]Fallback or default value for Content binding to ValueConverter
我有一個內容控件,可以根據當前狀態顯示動態內容。 一切正常,但是在設計時,我希望它顯示默認狀態。 有什么辦法可以使用ValueConverter
或FallbackValue
或其他方法執行此操作?
XAML
<ContentControl Content="{Binding State,
Converter={StaticResource InstallationStateToControlConverter}}" />
C#
class InstallationStateToControlConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
//return controls depending on the state
switch ((InstallationState)value)
{
case InstallationState.LicenceAgreement:
return new LicenceAgreementControl();
default:
return new AnotherControl();
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
更新
根據Viv的問題,我在XAML中添加了以下內容,它可以編譯,但在設計器中仍然看不到任何內容?
d:DataContext="{d:DesignInstance Type=local:LicenceAgreementControl, IsDesignTimeCreatable=True}"
好吧,我終於開始工作了,
這是評論中多項內容的結合。 希望這能為您解決。
假設所有運行時都很好,則可以查看ContentControl
顯示的模型並進行排序
這些是我所做的步驟。
ContentControl
Content
綁定值(在您的情況下為State
),以顯示默認的ViewModel。 例:
public LicenceAgreementControl() {
State = new NewViewModel();
}
d:DataContext
。 DataContext
分配給ContentControl
例:
<Window.Resources>
<local:LicenceAgreementControl x:Key="LicenceAgreementControl" />
</Window.Resources>
<ContentControl Content="{Binding State}" DataContext="{Binding Source={StaticResource LicenceAgreementControl}}" />
現在,只要您可以很好地看到設計時加載的視圖,我們就可以僅在設計時更新我們的方法,否則問題在於當前正在建立視圖模型的方式,需要首先進行分類
^^上面的東西工作正常。 要將其作為僅設計功能,請從xaml中刪除作為資源創建的視圖模型,還可以從ContentControl
刪除顯式的DataContext
集。
現在您需要的是
d:DataContext="{d:DesignInstance Type=local:LicenceAgreementControl, IsDesignTimeCreatable=True}"
在xaml文件中,您應該完成操作(仍然需要ctor設置State屬性為要在ContentControl
顯示的默認視圖模型)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.