我有一個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(另一個文件)嗎?
好的,所以我添加了一個依賴項屬性(枚舉在代碼後面)和一個樣式(在xaml中)以基於該屬性值更改模板。謝謝! –