mwjohnson
mwjohnson

Reputation: 661

Bind to a Property in the Data Context from a ListviewItem

I have a data context in the form of MyViewModel.

MyViewModel has a property: public int MyWidth.

For each item in my listview, that is ListViewItem, I need to display a canvas with a width equal to MyWidth.

My listView has it's ItemSource bound to a property called MyCollectionOfInts.

Which, as you may have guessed, is of the following definition: ObservableCollection<int>.

The astute reader has likely realized, the data context of myListView is int and thus fails when trying to bind the non-existant MyWidth property from the int type data-context.

What kind of theoretical crazy binding is necessary to get this kind of nutty thing to work?

My most recent attempt was to bind using RelativeSource but couldn't exactly figure it out...

My list View:

<ListView Name="MyListView" ItemsSource="{Binding MyCollectionOfInts}"

My Items within the List view.

  <ListView.View>
    <GridView>
      <GridView.Columns>
        <GridViewColumns Header=MyInts">
          <GridViewColumn.CellTemplate>
            <DataTemplate>
              <Label Name="m_TestLabel" Content="ASDF" />
                <TextBox Text="{Binding Path=MyWidth, RelativeSource=????{RelativeSource AncestorType={x:Type MyViewModel}}}"/>
            </DataTemplate>
</...a bunch of close brackets>

My list view Item is an int, but I want to get the Control's original data-context, ie. myViewModel, and bind the canvas width of my ListViewItem to the MyWidth property of myViewModel. How can I get the ListViewItem to recognize the control's data-context?

Note: I don't really want to make a container for the ListView and store a static MyWidth variable in it, but if that is the only way, then let me know. I'm hoping it's not.

Upvotes: 1

Views: 4180

Answers (2)

Reza ArabQaeni
Reza ArabQaeni

Reputation: 4907

<TextBox Text="{Binding Path=DataContext.MyWidth, 
RelativeSource={RelativeSource AncestorType={x:Type ListView }}}"/>

Or

<TextBox Text="{Binding Path=DataContext.MyWidth, 
 Source={x:Reference MyListView}"/>

Upvotes: 1

Nitin Purohit
Nitin Purohit

Reputation: 18580

Try this:

<TextBox Text="{Binding Path=DataContext.MyWidth, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"/>

If your View is usercontrol else use Window in type

Upvotes: 2

Related Questions