1

我正在尝试将事件链接到驻留在项目控件中的单选按钮。

我的模板如下:

<ItemsControl x:Name="RadioButtonsItemsControl" Height="auto" Width="auto" ItemsSource="{TemplateBinding MapLayers}" >

                        <ItemsControl.ItemsPanel>
                            <ItemsPanelTemplate>

                                <StackPanel Orientation="{TemplateBinding RadioButtonOrientation}" Margin="5"/>
                            </ItemsPanelTemplate>
                        </ItemsControl.ItemsPanel>

                        <ItemsControl.ItemTemplate>
                            <DataTemplate>

                                <RadioButton Content="{Binding ID}" IsChecked="{Binding Visible, Mode=TwoWay}"
                                    IsEnabled = "{Binding IsInScaleRange}"
                                    ToolTipService.ToolTip=""
                                    GroupName="BaseLayer"
                                    Foreground="{TemplateBinding ForeGroundBrush}" FontSize="11">

                                </RadioButton>
                            </DataTemplate>
                        </ItemsControl.ItemTemplate>
                    </ItemsControl>

在自定义控件的 .cs 文件中,我有一个用于 itemscontrol 的模板部分,并附加了事件

public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();

        radioButtonsItemsControl = GetTemplateChild("RadioButtonsItemsControl") as ItemsControl;
        if (radioButtonsItemsControl != null) radioButtonsItemsControl.MouseLeftButtonDown += radioButtonsItemsControlMouseLeftButtonDown;
    }

radioButtonsItemsControl 不等于 null (并且在此阶段尚未填充单选按钮),但 radioButtonsItemsControlMouseLeftButtonDown 事件仍应在稍后我单击项目控件时注册。

 void radioButtonsItemsControlMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        RadioButton radioButton = e.OriginalSource as RadioButton;
        if (radioButton != null) radioButton.Checked += OnChecked;
    }

当我单击我的项目控件时,这永远不会触发:radioButtonsItemsControlMouseLeftButtonDown。

不确定我是否以正确的方式进行此操作,因此我对将事件附加到 ItemsControls 内的项目的替代方法持开放态度。

谢谢,迈克

4

1 回答 1

0

一般来说,为了附加事件,我会做一个部分类扩展,并给它一个可以绑定的命令哈希表。在您的情况下,最简单的方法是定义和绑定列表后设置的事件。例如,集合上的属性 Visible 将检查是否定义了某个事件,如果是,则调用它。例如

创建一个事件来查看(OnRadioButtonChanged);加载列表后附加到事件。(一旦列表被清除以重新加载,就分离事件)。一旦事件存在,当可见性被切换时,它将调用发泄。代码示例如下:

public string Visibility
    {
        get
        {
            return __fVisibility;
        }
        set
        {
            __fVisibility = value;
            this.NotifyPropertyChanged("Visibility");
            if (!object.ReferenceEquals(OnVisibilityChanged, null))
                OnVisibilityChanged(null);
        }
    }

这对我来说是更清洁和更简单的解决方案。:)

于 2012-05-04T01:06:35.700 回答