1

データテンプレートのボタンにクリックイベントを追加したい。いくつかのコードがあります:

 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;

そのため、ボタンをクリックしても何も起こりません。私は何が欠けていますか?

4

1 に答える 1

0

この質問を見てください、それは非常に似ています。必要なものを取得するには、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");
    }
于 2012-08-07T11:08:55.813 に答える