簡體   English   中英

內容綁定到ValueConverter的后備或默認值

[英]Fallback or default value for Content binding to ValueConverter

我有一個內容控件,可以根據當前狀態顯示動態內容。 一切正常,但是在設計時,我希望它顯示默認狀態。 有什么辦法可以使用ValueConverterFallbackValue或其他方法執行此操作?

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();
}
  • 從主xaml文件中刪除所有出現的d:DataContext
  • 使用一些密鑰在xaml中將視圖模型創建為普通的舊資源,並將其作為DataContext分配給ContentControl

例:

<Window.Resources>
  <local:LicenceAgreementControl x:Key="LicenceAgreementControl" />
</Window.Resources>
<ContentControl Content="{Binding State}" DataContext="{Binding Source={StaticResource LicenceAgreementControl}}" />
  • 在您的視圖模型構造器中放置一個斷點
  • Expression Blend中的開放式解決方案
  • 現在在Visual Studio中,工具->附加到進程...->“在列表中選擇混合”->單擊附加
  • 切換回融合。 關閉並打開xaml文件。 您在Visual Studio中的斷點應被調用
  • 逐步執行過程中,我注意到調用了一個異常,該異常可以通過IsInDesignState檢查繞過。
  • 如果沒有例外,您應該在混合設計器中看到默認視圖模型的視圖加載(同樣適用於Visual Studio設計器)

現在,只要您可以很好地看到設計時加載的視圖,我們就可以僅在設計時更新我們的方法,否則問題在於當前正在建立視圖模型的方式,需要首先進行分類

^^上面的東西工作正常。 要將其作為僅設計功能,請從xaml中刪除作為資源創建的視圖模型,還可以從ContentControl刪除顯式的DataContext集。

現在您需要的是

d:DataContext="{d:DesignInstance Type=local:LicenceAgreementControl, IsDesignTimeCreatable=True}"

在xaml文件中,您應該完成操作(仍然需要ctor設置State屬性為要在ContentControl顯示的默認視圖模型)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM