Skip to main content
 首页 » 编程设计

c#之WPF。双态元素

2024年02月23日17EasonJim

我正在实现两个状态元素。我有两个 xaml(用于第一状态和第二状态)。我应该在单击鼠标时更改状态。

我创建自己的 Control child 并使用 xaml

 <Style TargetType="l:ActionButton"> 
    <Setter Property="Template"> 
        <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> 

在 OnApplyTemplate 我处理模板更改

    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; 
            }; 
 
        } 
 
    } 

但是当我用我的控件运行应用程序时,我得到:“已经添加了具有相同键的项目。”异常?

怎么了。我的方法对吗?

谢谢安德鲁

请您参考如下方法:

这绝对不是要走的路。如果您想要一个具有两个独立状态的控件,您应该重新设置 ToggleButton 的样式。您不想完全换掉 ControlTemplate,因为这真的很慢。相反,您可以将两个视觉对象放在同一个模板中,并根据状态显示/隐藏它们。

这就是 ToggleButton 的样式,它可以完成您所追求的(并且它不需要隐藏代码):

<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>