我正在尝试使用Style和ControlTemplate创建通用页面导航按钮。我们的想法是目标页面是按钮的CommandParameter:
<Button Height="64" Width="64" Style="{DynamicResource ButtonViewTileStyle}"
Command="{Binding Path=ChangePage}"
CommandParameter="{Binding Path=HomePage}"/>
...并且每个页面都有一个DisplayName和IconName属性,我想在ControlTemplate中使用它。这是一个只有显示名称的非工作示例:
<Style x:Key="ButtonViewTileStyle" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Canvas>
<TextBlock TextWrapping="Wrap"
Text="{Binding CommandParameter.DisplayName,
RelativeSource={RelativeSource TemplatedParent}}"
Canvas.Left="0" Canvas.Top="0"
HorizontalAlignment="Center" VerticalAlignment="Center"
Width="{TemplateBinding Width}"
Height="{TemplateBinding Height}"/>
</Canvas>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
有关Text = binding应该是什么的任何建议都可以使这个工作吗?
答案 0 :(得分:0)
请参阅以下代码。
<Window.Resources>
<Style x:Key="ButtonViewTileStyle" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Canvas>
<TextBlock TextWrapping="Wrap"
Text="{Binding CommandParameter.DisplayName,
RelativeSource={RelativeSource TemplatedParent}}"
Canvas.Left="0" Canvas.Top="0"
HorizontalAlignment="Center" VerticalAlignment="Center"
Width="{TemplateBinding Width}"
Height="{TemplateBinding Height}"/>
</Canvas>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<StackPanel>
<Button Command="{Binding TestCommand}" Width="100" Height="25" Style="{DynamicResource ButtonViewTileStyle}" CommandParameter="{Binding Path=PageDetails}"></Button>
</StackPanel>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new TestViewModel();
}
}
class TestViewModel
{
private CommndPrm pageDetials;
public CommndPrm PageDetails
{
get { return pageDetials; }
set { pageDetials = value; }
}
public TestViewModel()
{
pageDetials = new CommndPrm() { DisplayName="Test"};
}
}
class CommndPrm
{
private string displayName;
public string DisplayName
{
get { return displayName; }
set { displayName = value; }
}
}