DataTemplate中的XamlReader动态事件

时间:2012-08-07 08:31:01

标签: .net wpf xaml

想要将click事件添加到datatemplate中的按钮。 有一些代码:

 var temp = (DataTemplate)XamlReader.Load(
                   new MemoryStream(Encoding.Default.GetBytes(
                       @"<DataTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'><Button><TextBlock Text='1' TextAlignment='Center'/></Button></DataTemplate>"
                   )));
 var button = temp.LoadContent() as Button;
 button.Click += (sender, args) =>
                    {
                        MessageBox.Show("123");
                    };
 return temp;

所以,当我点击按钮时,没有任何反应。 我错过了什么?

1 个答案:

答案 0 :(得分:0)

看看this问题,它非常相似。为了得到你需要的东西你可以像这样使用Framework Element Factory:

private DataTemplate CreateTemplate()
    {
        FrameworkElementFactory fef = new FrameworkElementFactory(typeof(Button));//new FrameworkElementFactory("<Button Name='ButtonName'><TextBlock Text='1' TextAlignment='Center'/></Button>");
        fef.AddHandler(Button.ClickEvent, new RoutedEventHandler(b_Click));
        fef.SetValue(Button.ContentProperty, "1");

        return new DataTemplate() { VisualTree = fef };
    }

    private void b_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("123");
    }
相关问题