如何从控件中弹出 class 字段?

How to eject the class fields from control?

我有自己的用户控件。此控件的代码:

<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 绑定到我的 class 对象列表。我的 class:

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 class 对象信息(例如,“09984”、“10.3.0.17”)。像这样:

void watchBut_Click(object sender, RoutedEventArgs e)
{
    var myItem = ((Button)sender).DataContext as MyItem;

    //  Do stuff
}

您可以 give MyItem a property that returns a Command 并将数据上下文作为命令参数发送:

<Button 
    Name="watchBut" 
    Grid.Row="1" 
    Style="{StaticResource RoundButtonTemplate}" 
    Margin="5,0,5,5" 
    FontSize="15" 
    Content="Watch" 
    Command="{Binding WatchCommand}"
    CommandParameter="{Binding}"
    />

没有路径的绑定只是将 DataContext 本身(在本例中为 MyItem 的实例)绑定到 属性。那是 "better",更纯粹的 MVVM 解决方案,但您在这里做的不是非常纯粹的 MVVM,事件处理程序也不是大罪。