如何检索由DataTemplate创建的控件?

时间:2018-11-14 17:00:11

标签: c# wpf xaml

我有一个对象列表,需要将其表示为按钮列表。 这些按钮通常应充当常规按钮;选中该复选框时,它们应作为ToggleButtons并保持按下状态。但是我还需要它们相互排斥,例如RadioButton(只能在任何时候切换一个)。

我尝试使用RadioButton作为ItemsControl的模板,但它们并不互斥(我想它们实际上不是同一控件的子级)。

因此,我想使用ToggleButton作为模板,如果未选中此复选框,则手动取消选中它,并手动处理互斥。 但是,我找不到一种方法来检索列表中其他项目的切换按钮以取消选中它们。

这是我的XAML:

<Window x:Class="WpfApp9.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">

<UniformGrid Rows="1">
    <UniformGrid.Resources>          
        <DataTemplate x:Key="template">
            <ToggleButton Name="Toggle"                              
                          Checked="ToggleButton_Checked"
                          Content="{Binding}"/>
        </DataTemplate>
    </UniformGrid.Resources>

    <ItemsControl Name="lst" ItemTemplate="{StaticResource template}" />

    <CheckBox Name="CheckToggle"
              HorizontalAlignment="Center"
              VerticalAlignment="Center">
        TOGGLE
    </CheckBox>
</UniformGrid>
</Window>

这是我的代码背后:

using System.Windows;
using System.Windows.Controls.Primitives;

namespace WpfApp9
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            lst.ItemsSource = new[] { "foo", "bar", "baz" };
        }

        private void ToggleButton_Checked(object sender, RoutedEventArgs e)
        {
            var toggle = (ToggleButton)sender;

            // If the checkbox is not checked, release the button immediately
            if (CheckToggle.IsChecked != true)
                toggle.IsChecked = false;

            // now how do I uncheck the other ToggleButtons?
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我最终以不同的方式解决了上述问题。 在问题中我说了

  

我尝试使用RadioButton作为ItemsControl的模板,但它们并不互斥(我想它们实际上不是同一控件的子级)

但是我没有意识到我可以使用GroupName属性来将它们强制放入同一组。此时,模板可以是这样的:

    <DataTemplate x:Key="template">
        <RadioButton Checked="RadioButton_Checked"
                     GroupName="SomeGroupName"
                     Content="{Binding}"/>
    </DataTemplate>

我得到了互斥的按钮,而无需手动处理。