我有自己的用户控件。这个控件的代码:
<StackPanel>
<TextBlock Text="{Binding Login}" Margin="0,18,0,0" HorizontalAlignment="Center" FontWeight="Bold"/>
<TextBlock Text="{Binding Address}" HorizontalAlignment="Center" />
</StackPanel>
</Border>
<Button Name="watchBut" Grid.Row="1" Style="{StaticResource RoundButtonTemplate}" Margin="5,0,5,5" FontSize="15" Content="Watch" Click="watchBut_Click"/>
我创建它来制作这些控件的网格,它看起来像这样:
此网格是ItemsControl。它的代码:
<ItemsControl Name="items" Margin="5,-5,5,5" Grid.Column="1" Grid.Row="1">
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:MyControl />
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
在代码中,这个ItemsControl被绑定到我的类对象的List。我的班级:
class MyItem
{
public int Id { set; get; }
public string Login { set; get; }
public string Address { set; get; }
public MyItem(int Id, string Login, string Address)
{
this.Id = Id;
this.Login = Login;
this.Address = Address;
}
}
如何填充:
List<MyItem> Computers = new List<MyItem>
{
new MyItem(0,"08739","10.3.0.9"),
new MyItem(1,"08813","10.3.0.11"),
new MyItem(2,"09832","10.3.0.14"),
new MyItem(3,"09854","10.3.0.12"),
new MyItem(4,"09984","10.3.0.17"),
new MyItem(5,"proskurin","10.3.0.1"),
new MyItem(6,"karavaev","10.3.0.2"),
new MyItem(7,"deba","10.3.0.13")
};
items.ItemsSource = Computers;
我想通过单击此矩形下的“Watch”按钮获取MyItem类对象信息(例如,“09984”,“10.3.0.17”)。像这样:
答案 0 :(得分:0)
void watchBut_Click(object sender, RoutedEventArgs e)
{
var myItem = ((Button)sender).DataContext as MyItem;
// Do stuff
}
您可以改为give MyItem a property that returns a Command并将datacontext作为命令参数发送:
<Button
Name="watchBut"
Grid.Row="1"
Style="{StaticResource RoundButtonTemplate}"
Margin="5,0,5,5"
FontSize="15"
Content="Watch"
Command="{Binding WatchCommand}"
CommandParameter="{Binding}"
/>
没有Path的绑定只是将DataContext本身(在这种情况下为MyItem
的实例)绑定到属性。这是“更好”,更纯粹的MVVM解决方案,但你不是在这里做非常纯粹的MVVM而且事件处理程序不是致命的罪。