就像Yacoder說的那樣,有絕對是這是一個更優雅的方法。但是,如果你想要去的動態域名的辦法,你應該能夠使它工作使用的附加屬性,像這樣:
namespace ListBoxExample
{
public static class TagAttach
{
public static readonly System.Windows.DependencyProperty TagProperty =
System.Windows.DependencyProperty.RegisterAttached(
"Tag", typeof (string), typeof (TagAttach));
public static void SetTag(System.Windows.UIElement element, string value)
{
element.SetValue(TagProperty, value);
}
public static string GetTag(System.Windows.UIElement element)
{
return (string)element.GetValue(TagProperty);
}
}
}
<Window x:Class="ListBoxExample.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="clr-namespace:ListBoxExample"
Title="Window1" Height="300" Width="300">
<Grid>
<ListBox ItemsSource="{Binding}" Grid.IsSharedSizeScope="True">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition SharedSizeGroup="A" />
<ColumnDefinition SharedSizeGroup="B" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding Position}"/>
<Label Grid.Column="1" Content="{Binding Name}" FontSize="18" Margin="0,10,0,0" />
<WrapPanel Grid.Column="2" >
<Button Click="MoveUpClick" loc:TagAttach.Tag="{Binding Name}">Up</Button>
<Button Click="MoveDownClick" loc:TagAttach.Tag="{Binding Name}">Down</Button>
</WrapPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
namespace ListBoxExample
{
public partial class Window1
{
public Window1()
{
InitializeComponent();
DataContext = new[]
{
new {Name = "Tom", Position = "Butcher"},
new {Name = "Dick", Position = "Baker"},
new {Name = "Harry", Position = "Candlestick Maker"}
};
}
private void MoveUpClick(object sender, System.Windows.RoutedEventArgs e)
{
System.Windows.MessageBox.Show("Up - " + TagAttach.GetTag(sender as System.Windows.UIElement));
}
private void MoveDownClick(object sender, System.Windows.RoutedEventArgs e)
{
System.Windows.MessageBox.Show("Down - " + TagAttach.GetTag(sender as System.Windows.UIElement));
}
}
}
馬克,你爲什麼需要知道按鈕的名稱?它似乎不是「真正的WPF方式」... ... – 2009-09-17 17:56:36
(只是不要誤解我的意思,我正在嘗試提供幫助,只是可能會有更好的方式來做WPF中的竅門,沒有文字東西) – 2009-09-17 18:00:01
每個ListBoxItem有兩個按鈕,所以當我得到一個ClickEvent時,我需要知道什麼ListBoxItem與我單擊的按鈕「關聯」。我幾乎可以肯定,有一種更優雅的方式來做到這一點,因爲我時間不夠。如果有人有類型解釋這種做法的正確方法,我會很高興。 – Mark 2009-09-17 18:04:58