如何在代码后面的两个数据模板之间切换

问题描述 投票:0回答:1

我有一个包含两个数据模板的资源字典。每个模板都有一个带有对象的堆栈面板。

在基于我从其他地方获得的条件的隐藏代码中,我想将这些堆栈面板之一嵌入到占位符网格中。看起来很简单,除了我有一个 ItemClick 事件需要 x:class 或其他东西。

//toggle.xaml
<ResourceDictionary .....>

   <DataTemplate x:Key="A">
     <StackPanel>
       ..Tab control with certain tabs with a button with a click event
     </StackPanel>
   </DataTemplate>

   <DataTemplate x:Key="B">
     <StackPanel>
       ..Tab control with with certain button with a click event
     </StackPanel>
   </DataTemplate>

</ResourceDictionary>
//in MainWindow.cs

<Window.....>
  <Window.Resources>
     <ResourceDictionary Source ="/toggle.xaml"
  </Window.Resources>

  <Grid x:Name="myGrid" />
  
</Window>
//in my MainWindow.xaml.cs code behind

var dictionary = (ResourceDictionary)Application.LoadComponent("/toggle.xaml", UriKind.Relative));
String key = "A";

if (certainConditionExists)
{
   key = "B";
}

var template = (DataTemplate)dictionary[key];
var panel = (StackPanel)template.Resources[key];
myGrid.Children.Add(panel);

错误: “ResourceDictionary”根元素需要 x:Class 属性来支持 XAML 文件中的事件处理程序

c# wpf datatemplate resourcedictionary
1个回答
0
投票

我认为你选择解决问题的方式是有问题的。我无法给你任何确切的结论,因为你还没有写任何关于任务本身的内容。

至于直接回答你的问题,有几种可能的解决方案。 我将向您展示两种方法:

  1. 静态点击处理程序(点击器)。
  2. 已注册的 RoutedCommand。
    public static partial class SomeHelper
    {
        public static RoutedEventHandler SomeClicker { get; } = (s, _) =>
        {
            Button button = (Button)s;
            MessageBox.Show(button.CommandParameter?.ToString(), "Static Clicker");
        };


        private static RoutedUICommand _messageCommand;
        public static RoutedUICommand MessageCommand
        {
            get
            {
                if (_messageCommand == null)
                {
                    _messageCommand = new RoutedUICommand("Show Message", nameof(MessageCommand), typeof(SomeHelper));
                    CommandManager.RegisterClassCommandBinding(typeof(Window), new CommandBinding(_messageCommand, OnMessageExecute));
                }
                return _messageCommand;
            }
        }

        private static void OnMessageExecute(object sender, ExecutedRoutedEventArgs e)
        {
            MessageBox.Show(e.Parameter?.ToString(), "CommandBinding");
        }
    }
    <Button Content="First"
            Click="{x:Static local:SomeHelper.SomeClicker}"
            CommandParameter="Message One"/>

    <Button Content="Second"
            Click="{x:Static local:SomeHelper.MessageCommand}"
            CommandParameter="Message Two"/>

如有必要,可以一键组合两种变体。在这种情况下,将首先执行 Clicker,然后执行命令。

© www.soinside.com 2019 - 2024. All rights reserved.