iknow
iknow

Reputation: 9862

ItemsControl and DataTemplate binding to itself

I have Window with ViewModel which has ObservableCollection<SomeObject> named Collection. SomeObject contains two fields named: Property1 and Property2. To that window, I want to add UserControls. UserControl has two dependency properties also named: Property1 and Property2. In the window xaml file I created ItemsControl like this:

<ItemsControl
    ItemsSource="{Binding Collection}">

    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel>

            </StackPanel>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>

    <ItemsControl.ItemTemplate>

        <DataTemplate>
            <local:SomeUserControl
                Property1="{Binding Path=Property1}"
                Property2="{Binding Path=Property2}"/>
        </DataTemplate>

    </ItemsControl.ItemTemplate>

</ItemsControl>

Is this possible to have just one dependency property SomeObject in UserControl and bind it in DataTemlete? Something like this:

<DataTemplate>
    <local:SomeUserControl
        SomeObject="{Binding Path=this}"/>
</DataTemplate>

this means object from Collection (defined in ItemsSource="{Binding Collection}). So basically it's just binding to itself.


Edit: the idea I have just got now:

In the SomeObject class define getter:

public SomeObject GetItself => this

and then in DataTemplate I can use: SomeObject="{Binding Path=GetItself}". It is working but I think that there has to be a better way to reach this without creating GetIteself field.

Upvotes: 0

Views: 912

Answers (1)

Ahmad
Ahmad

Reputation: 38

I think it works

<DataTemplate>
    <local:SomeUserControl
        SomeObject="{Binding .}"/>
</DataTemplate>

or just

<DataTemplate>
    <local:SomeUserControl
        SomeObject="{Binding}"/>
</DataTemplate>

Upvotes: 1

Related Questions