Search code examples
c#itemssource

How to eject the class fields from control?


I have my own user control. This control's code:

<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"/>

I created it to make a grid of these controls, it looks like this:

enter image description here

This grid is ItemsControl. Its code:

<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>

In the code this ItemsControl is binded to List of my class objects. My 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;
    }
}

How it is populated:

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;

I want to get MyItem class object information (for example, "09984", "10.3.0.17") by clicking the button "Watch" under this rectangle. Something like this:


Solution

  • void watchBut_Click(object sender, RoutedEventArgs e)
    {
        var myItem = ((Button)sender).DataContext as MyItem;
    
        //  Do stuff
    }
    

    You could instead give MyItem a property that returns a Command and send the datacontext as the command parameter:

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

    A binding without a Path just binds the DataContext itself (the instance of MyItem in this case) to the property. That's the "better", more pure-MVVM solution, but you're not doing very pure MVVM here and event handlers aren't a mortal sin.