0

我知道,如何在 C# 代码中在运行时创建数据模板:

string xaml =
@"<DataTemplate
xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
...
...
</DataTemplate>";

DataTemplate dt = (DataTemplate)XamlReader.Load(xaml);

但是我怎样才能将事件添加到这个模板中,我应该在哪里定义事件处理程序。

4

2 回答 2

0

我找到了一个解决方案:

LongListMultiSelector LLMS = new LongListMultiSelector();
LLMS.ItemTemplate = CreateDataTemplate();
LLMS.ItemsSource = ExampleList;

浏览我的 LongListMultiSelector 中的所有项目:

int number = 0;
for(int i; i<ExampleList.Count; i++)
{
    number = 0;
    StackPanel sp = FindElementInVisualTree<StackPanel>(LLMS, i);
    sp.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(StackPanel_Tap);
}

此方法在具有索引的父元素中查找元素:

private T FindElementInVisualTree<T>(DependencyObject parentElement, int ind) where T : DependencyObject
{
        var count = VisualTreeHelper.GetChildrenCount(parentElement);
        if (count == 0) 
            return null;

        for (int i = 0; i < count; i++)
        {
            var child = VisualTreeHelper.GetChild(parentElement, i);
            if (child != null && child is T)
            {
                if (number == ind)
                {
                    number = 0;
                    return (T)child;
                }
                number++;
            }
            else
            {
                var result = FindElementInVisualTree<T>(child, ind);
                if (result != null)
                    return result;
            }
        }
        return null;
}

private DataTemplate CreateDataTemplate()
{
    string xaml =
        @"<DataTemplate
        xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
        xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">

            <StackPanel>
                <TextBlock Text='{Binding Title}'/>
                ...
                ...
            </StackPanel>
        </DataTemplate>";

    DataTemplate dt = (DataTemplate)XamlReader.Load(xaml);

    return dt;
}
于 2013-10-31T13:40:56.690 回答
0

最简单的方法是:

例如,您有一个 ListBox:

testLisBox.ItemTemplate = CreateTemplate();
testLisBox.ItemsSource = new[] { "Item1", "Item2" };    
testLisBox.AddHandler(Button.ClickEvent, new RoutedEventHandler(buttonClick));

private DataTemplate CreateTemplate()
        {          
            string xaml =
@"<DataTemplate
xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
<Button Name=""testbutton"">123123</Button>
</DataTemplate>";
            return (DataTemplate)System.Windows.Markup.XamlReader.Load(new MemoryStream(Encoding.UTF8.GetBytes(xaml)));            
        }

private void buttonClick(object sender, RoutedEventArgs e)
        {
            if (e.OriginalSource is Button && ((Button)e.OriginalSource).Name == "testbutton")
            {
                MessageBox.Show("123");    
            }            
        }
于 2013-10-31T12:55:42.037 回答