动态显示/显示wpf内容

时间:2012-08-29 16:33:12

标签: wpf xaml togglebutton contentcontrol

正如标题所说,我想隐藏或动态显示一些内容。我有两个按钮像单选按钮一样工作。每个按钮都必须显示一个特定的内容,但这两个内容不能同时显示(它是一种形式,我正在处理两个子类)。

我在SO上看过两件有趣的事情,我想混合它们。首先,使用带有ToggleButton的ContentControl(http://stackoverflow.com/questions/7698560/how-to-bind-click-of-a-button-to-change-the-content-of-a-panel-网格使用-XAML)。其次,使用ToggleButtons作为RadioButtons(http://stackoverflow.com/questions/2362641/how-to-get-a-group-of-toggle-buttons-to-act-like-radio-buttons-in-wpf第二个答案与31)

所以我决定从这样的事情开始:

<ContentControl>
    <ContentControl.Template>
        <ControlTemplate>
            <WrapPanel HorizontalAlignment="Center">
                <TextBlock Text="{x:Static Internationalization:Resources.MAINOPTIONSWINDOW_STATUSLINKSUPERVISOR}"/>
                <RadioButton Style="{StaticResource {x:Type ToggleButton}}" Content="Alarm" GroupName="Trigger"/>
                <RadioButton Style="{StaticResource {x:Type ToggleButton}}" Content="Event" GroupName="Trigger"/>

            </WrapPanel>
        </ControlTemplate>
    </ContentControl.Template>
</ContentControl>

但Visual Studio强调

{StaticResource {x:Type ToggleButton}}

在视觉上,我的按钮显示为单选按钮而不是切换按钮。 视觉说:

  

无法解析资源“{StaticResource {x:Type   ToggleButton}}“(翻译自法语;))

无论如何,这段代码在ContentControl之外正常工作。

3 个答案:

答案 0 :(得分:1)

是的,首先,修复你的eventHandlers。不要将它们附加在模板上,可能会发生棘手的事情。

其次,您可以修改ContentControl.Resources,并将其放到那里:

<Style BasedOn="{StaticResource {x:Type ToggleButton}}"
          TargetType="RadioButton"/>

删除自己的样式定义。你甚至可以把这一级更高(ContentControl的父级)。还有一件事,你在代码隐藏中做这件事,但我可以向你保证,WPF的真正力量源于你不需要代码隐藏,至少是这样的逻辑。

您提供的链接也是使用触发器。现在这不是什么大事,但你应该知道这不是正确的方法。如果您想在内容之间切换,请查看ContentControl内容,DataTemplates,DataTemplateSelector。这个想法是在内存中只有一个VIEW,而不是隐藏东西。

如果你正在做另外的事情,那可以赶上来。它最终将为启动和内存使用增加更多时间。

答案 1 :(得分:0)

在控件模板中,您通常不会添加事件处理程序。

重写OnApplyTemplate并在那里添加处理程序。

答案 2 :(得分:0)

我终于找到了另一种方式

<RadioButton Content="Alarm" GroupName="TriggerStateInfo" Style="{StaticResource {x:Type ToggleButton}}"
      Command="{x:Static StateInfoTemplateToAlarmCommand}"/>
<RadioButton Content="Event" GroupName="TriggerStateInfo" Style="{StaticResource {x:Type ToggleButton}}"
              Command="{x:Static StateInfoTemplateToEventCommand}"/>
<ContentControl Content="{Binding Path=Trigger, ElementName=Window}">
    <ContentControl.Resources>
        <DataTemplate DataType="{x:Type States:AlarmTrigger}">
            <ComboBox ItemsSource="{Binding Path=AlarmTriggersCollection}" />
        </DataTemplate>
        <DataTemplate DataType="{x:Type States:EventTrigger}">
            <ComboBox ItemsSource="{Binding Path=EventTriggersCollection}" />
        </DataTemplate>
    </ContentControl.Resources>
</ContentControl>

代码隐藏更改触发器类型