(WPF MVVM)我正在尝试使用我自己的Style以及ContentTemplate-> StaticResource-> DataTemplate的组合来制作暂停/播放按钮。我将DataTemplate设置为矢量图形数据。我为Pause-Button和Play-Button准备了2个矢量图形。 我的目标:如果我点击暂停按钮,ContentTemplate将“切换”到Play-Button-DataTemplate,按钮变为Play-Button。 我知道我需要绑定按钮的Click-event或使用RelayCommand进行暂停/播放操作(在我的代码片段中我没有绑定Click事件),但我不知道如何绑定ContentTemplate获得我需要的效果。提前谢谢。
<controls:MyButton x:Name="btnPause" AutomationProperties.Name="btnPause" Style="{StaticResource MyButtonStyle}" ContentTemplate="{StaticResource dtmpPause}" />
<DataTemplate x:Name="dtmpPause">
<Path x:Name="pathPause" Fill="White" Stretch="Uniform" Data="M314.00598,126.271 L379.52698,126.271 L379.52698,440.672 L314.00598,440.672 z M187.40198,126.271 L252.92398,126.271 L252.92398,440.672 L187.40198,440.672 z M283.45901,34.240997 C146.03,34.240997 34.229004,146.043 34.229004,283.45697 C34.229004,420.88702 146.03,532.70099 283.45901,532.70099 C420.88699,532.70099 532.70203,420.88702 532.70203,283.45697 C532.70203,146.043 420.88699,34.240997 283.45901,34.240997 z M283.45901,0 C439.772,0 566.92999,127.158 566.92999,283.45697 C566.92999,439.771 439.772,566.94299 283.45901,566.94299 C127.15799,566.94299 0,439.771 0,283.45697 C0,127.158 127.15799,0 283.45901,0 z"/>
</DataTemplate>
<DataTemplate x:Name="dtmpPlay">
<Path x:Name="pathPlay" Fill="White" Stretch="Uniform" Data="M269.00003,121.50002 L298.00003,121.50002 L298.00003,445.50003 L269.00003,445.50003 z M283.5,41.621429 L41.620132,283.50198 L283.5,525.37958 L525.37982,283.50198 z M283.5,0 L566.99994,283.50198 L283.5,567 L0,283.50198 z"/>
</DataTemplate>
答案 0 :(得分:1)
使用DataTemplateSelector,它允许您按照您定义的条件选择您想要的DataTemplate,无论您希望如何实现。
以下是一个例子:
public class TaskListDataTemplateSelector : DataTemplateSelector
{
public override DataTemplate
SelectTemplate(object item, DependencyObject container)
{
FrameworkElement element = container as FrameworkElement;
if (element != null && item != null && item is Task)
{
Task taskitem = item as Task;
if (taskitem.Priority == 1)
return
element.FindResource("importantTaskTemplate") as DataTemplate;
else
return
element.FindResource("myTaskTemplate") as DataTemplate;
}
return null;
}
}
在这个例子中,你根据DataContext的优先级返回你想要的任何DataTemplate。
在xaml中,您需要告诉控件它应该使用哪个DataTemplateSelector:
<ListBox Width="400" Margin="10"
ItemsSource="{Binding Source={StaticResource myTodoList}}"
ItemTemplateSelector="{StaticResource myDataTemplateSelector}"
HorizontalContentAlignment="Stretch"/>
在这种情况下,ListBox将使用myDataTemplateSelector。
在你的情况下是MyButton。