WPF. TwoState element
I'm implementing two state element. I have two xaml's (for first state and second state). I should change state at mouse click.
I create own Control child and use xaml
<Style TargetType="l:ActionButton">
<Setter Property="Tem开发者_开发百科plate">
<Setter.Value>
<ControlTemplate TargetType="l:ActionButton">
<ContentControl x:Name="LayoutRoot">
<ContentControl.Resources>
<ControlTemplate x:Key="buttonDownTemplate">
<Canvas>.....</Canvas>
</ControlTemplate>
<ControlTemplate x:Key="buttonUpTemplate">
<Canvas>.....<Canvas>
</ControlTemplate>
</ContentControl.Resources>
</ContentControl>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
At OnApplyTemplate I handle template changing
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
var btn = GetTemplateChild("LayoutRoot") as ContentControl;
if (btn != null)
{
btn.MouseLeftButtonDown += (o, e) =>
{
//sample change template
var template = (ControlTemplate)btn.FindResource("buttonDownTemplate");
this.Template = template;
};
}
}
But when I run app with my control I get: "An item with the same key has already been added." exception?
What's wrong. Is my way right?
Thanks, Andrew
This is definitely not the way to go. If you want a control that has two separate states, you should just restyle the ToggleButton
. You don't want completely swap out the ControlTemplate, as this is really slow. Instead, you would put both of the visuals in the same template and show / hide them based on the state.
This is what a style for a ToggleButton would look like that accomplishes what you're after (and it requires no code behind):
<Style x:Key="twoStateButton" TargetType="{x:Type ToggleButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ToggleButton}">
<Grid>
<Canvas x:Name="buttonDownTemplate" Background="#202020" Visibility="Collapsed">
...
</Canvas>
<Canvas x:Name="buttonUpTemplate" Background="#C0C0C0">
...
</Canvas>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter TargetName="buttonDownTemplate" Property="Visibility" Value="Visible" />
<Setter TargetName="buttonUpTemplate" Property="Visibility" Value="Collapsed" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
精彩评论