我对 WPF/XAML 有点陌生(虽然我学过 C#),非常感谢对我的问题有任何帮助。我确实浏览了其他帖子和谷歌一段时间,但我似乎找不到令人满意或详细的答案来让我继续我的项目。请在下面查看详细信息。提前谢谢你!
客观的
我有一个名为 Tile 的类,它由一些属性和一个事件处理程序组成。我还有一个 ItemControl,它有一个按钮(如 DataTemplate),它的 ItemSource 是 Tiles 的集合。
现在,我想绑定 Button 的“Click”事件,以便调用 Tile 类中定义的 Event Handler 方法。
换句话说,当我单击 ItemControl 中任何项目的按钮时,必须调用相应 Tile 实例(来自集合)的方法处理程序。我将如何解决这个问题?
下面是完整的代码,为避免分心而进行了简化:
XAML
<Window x:Class="SampleWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="300" Width="300">
<!-- Make a ItemControl for "Tile"s. -->
<ItemsControl x:Name="TileList">
<ItemsControl.ItemTemplate>
<DataTemplate>
<!-- Wire the click event of this Button
to event handler in the Tile class. -->
<Button Content="Show"></Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Window>
代码隐藏
namespace SampleWPF
{
public partial class MainWindow : Window
{
ObservableCollection<Tile> tiles;
public MainWindow()
{
InitializeComponent();
// Adding some sample data for testing.
tiles = new ObservableCollection<Tile>();
tiles.Add(new Tile("Item 1"));
tiles.Add(new Tile("Item 2"));
TileList.ItemsSource = tiles;
}
}
public class Tile : INotifyPropertyChanged
{
public string Data
{ /* Accessors and PropertyNotifiers */ }
public Tile(string data)
{ /* Initializing and assigning "Data" */ }
// INotifyPropertyChanged implementation...
// { ... }
// This event handler should be bound to the Button's "Click" event
// in the DataTemplate of the Item.
public void ShowButton_Click(object sender, EventArgs e)
{
MessageBox.Show("Viewing item from: " + this.Data);
}
}
}
因此,如果我单击第一个“显示”按钮,输出应该是“查看项目来自:项目 1”,如果我单击第二个“显示”按钮,输出应该是“查看项目来自:项目 2”。
那么推荐/有效的方法是什么?我的代码不适合这个要求吗?