2015-04-23 44 views
0

我有一個UserControl我想在窗口的某些部分顯示不同的控件模板。但我想將這些模板放在UserControl本身內部(爲了更好的維護)。那就是:在WPF中,可以爲UserControl內部的UserControl定義一個ControlTemplate(在VS中不會收到警告/錯誤)?

<UserControl x:Class="PruebasDeWPF.MyUserControl" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:local="clr-namespace:PruebasDeWPF" 
     mc:Ignorable="d" 
     d:DesignHeight="300" d:DesignWidth="300"> 
<UserControl.Resources> 
    <ControlTemplate x:Key="UserControlTemplate1" TargetType="local:MyUserControl"> 
     <Grid> 
      <Rectangle Fill="Red"></Rectangle> 
     </Grid> 
    </ControlTemplate> 
    <ControlTemplate x:Key="UserControlTemplate2" TargetType="local:MyUserControl"> 
     <Grid> 
      <Rectangle Fill="Blue"></Rectangle> 
     </Grid> 
    </ControlTemplate> 
</UserControl.Resources> 
<Grid> 

</Grid> 

現在,當我使用它:

<Window x:Class="PruebasDeWPF.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:local="clr-namespace:PruebasDeWPF" 
     mc:Ignorable="d" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
     <local:MyUserControl Template="{StaticResource UserControlTemplate1}"></local:MyUserControl> 
    </Grid> 
</Window> 

我得到一個錯誤,在Visual Studio中說,資源無法被發現和控制沒有顯示出來。如果我將模板更改爲DynamicResource,則會收到與警告相同的消息,但控件顯示。無論如何,該程序運行良好。那麼如何將UserControl及其模板保留在一起而不會產生這些惱人的警告/錯誤?我需要一個特定的ResourceDictionary(另一個文件)嗎?

回答

0

您嘗試使用的模式由於加載方式而不太適合資源:作爲自上而下的樹。要在內部定義的選項之間切換,在您的UserControl(如果要綁定它的話)上定義一個屬性會更合適,這可能指示應使用哪個可用模板。這可能是一個字符串,一個數字或(可能是最好的選項)enum列出可用的選項。在UserControl的內部,您可以根據該值切換使用的內部定義的模板。這個基本的方法用於各種框架控件 - 例如Slider.Orientation

+0

好的,所以我添加了一個依賴項屬性(枚舉在代碼後面)和一個樣式(在xaml中)以基於該屬性值更改模板。謝謝! –

0

你正在做什麼不適用於UserControl。

嘗試查找用於創建CustomControls的文章。

基本上,您將創建一個新的類(只是一個類),繼承自ContentControl,並使用名爲「ContentTemplate」的屬性,就像在您提供的代碼示例中使用「Template」屬性一樣。

如果您有任何具體的邏輯在你的控制應用,覆蓋OnApplyTemplate方法

0

如果存儲控制在模板話,我不認爲你可以使用它作爲一個靜態資源。請參閱:https://msdn.microsoft.com/en-us/library/hh758287.aspx

試圖指定的StaticResource到無法解析 的關鍵在運行時拋出一個XAML解析異常。

您的控件在加載期間不存在,所以模板不存在,因此對模板不存在的鍵的引用失敗。

DynamicResources僅在運行時解決,這就是您的程序運行但出現警告的原因。設計師的警告說'我現在找不到這個,但可能能夠在程序運行時'。

相關問題