如何在动态数据模板中添加处理程序

发布于 2024-08-28 03:54:43 字数 1057 浏览 5 评论 0原文

我成功地在后面的代码中声明了一个数据模板,如下所示:

    private static DataTemplate CreateTemplate(string sortMemberPath, HorizontalAlignment horzAlignment)
    {
        const string xamlFormat
            =
            "<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" >"
            + "<StackPanel > "
            + "  <TextBlock Margin=\"2,0\" VerticalAlignment=\"Center\"  HorizontalAlignment=\"_HALIGNMENT_\"  "
            +
            "              Text=\"hello there\">   "
            + "  </TextBlock> "
            + "</StackPanel>"
            + "</DataTemplate>";

        return (DataTemplate) XamlReader.Load(xamlReturned);
    }

但现在我想通过更改以下行来添加大小更改处理程序:

            + "<StackPanel > "

            + "<StackPanel  SizeChanged="SizeChangedHandler" > "

在后面的代码中声明了方法“SizeChangedHandler”。当控件尝试在运行时加载时,这会导致 xaml 解析错误。我怀疑它找不到处理程序“SizeChangedHandler”。我怎样才能指定这个处理程序,以便 xaml 解析器满意。

I am successfully declaring a data template in a code behind as follows:

    private static DataTemplate CreateTemplate(string sortMemberPath, HorizontalAlignment horzAlignment)
    {
        const string xamlFormat
            =
            "<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" >"
            + "<StackPanel > "
            + "  <TextBlock Margin=\"2,0\" VerticalAlignment=\"Center\"  HorizontalAlignment=\"_HALIGNMENT_\"  "
            +
            "              Text=\"hello there\">   "
            + "  </TextBlock> "
            + "</StackPanel>"
            + "</DataTemplate>";

        return (DataTemplate) XamlReader.Load(xamlReturned);
    }

But now I want to add a size changed handler by changing the line:

            + "<StackPanel > "

to

            + "<StackPanel  SizeChanged="SizeChangedHandler" > "

I have the method "SizeChangedHandler" declared in the code behind. This results in a xaml parse error when the control attempts to load at runtime. I suspect that it can't find the handler "SizeChangedHandler". How can I specify this handler so that the xaml parser is happy.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

没有心的人 2024-09-04 03:54:43

您可以尝试类似的操作:

  dataTemplate.VisualTree.AddHandler(StackPanel.SizeChangedEvent, new SizeChangedEventHandler(SizeChangedHandler));

编辑:

好的,对于 Silverlight,您可以尝试使用 LoadContent 方法返回 DataTemplate 和可以附加事件的 UIElement。抱歉,我没有准备好 VS 来测试它是否可以工作。

You could try something like:

  dataTemplate.VisualTree.AddHandler(StackPanel.SizeChangedEvent, new SizeChangedEventHandler(SizeChangedHandler));

Edit:

Ok, for Silverlight you could try with the LoadContent method of the DataTemplate that returns and UIElement to which you can atach the event. Sorry I don't have VS ready to test and see if it works atm.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文