Jay Tennant
Jay Tennant

Reputation: 201

How do I access the item of a ItemsControl's item bound to a UserControl?

(I'm struggling to clearly ask my question, sorry if it's not clear.)

I want to access the item of an ItemsControl that is bound to a UserControl, but I don't know what property it is bound to. Here's an example:

<ItemsControl ItemsSource="{Binding Path=Widgets}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <local:WidgetView/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

where "Widgets" is a collection of the following class instances:

public class Widget
{
    public int Data { get; set; }
    public int OtherData { get; set; }
    public Widget() {}
}

and "WidgetView" is a UserControl:

<UserControl x:Class="TestApp.WidgetView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:TestApp">
    <WrapPanel>
        <TextBlock Text="{Binding Path=Data, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
        <Button Content="Set Other Data" Click="btn_clicked"/>
    </WrapPanel>
</UserControl>

with code-behind:

public partial class WidgetView : UserControl
{
    public WidgetView() {}
    private void btn_clicked(object sender, RoutedEventArgs e)
    {
        (???).OtherData = 42;
    }
}

In the code-behind, how would I access the "Widget" instance the "WidgetView" is bound to in the ItemsControl?

Upvotes: 2

Views: 59

Answers (1)

BradleyDotNET
BradleyDotNET

Reputation: 61339

As Crowcoder said; you would typically do this via ICommand and not have the code-behind involved.

That being said; for the few times you need this method you access it via DataContext. That's an object, so you'll need to cast:

private void btn_clicked(object sender, RoutedEventArgs e)
    {
         var widget = (Widget)DataContext; //Or a safer cast!
         widget.OtherData = 42;
    }

Upvotes: 2

Related Questions