开发者

Exposing DataGrid SelectedItem in parent UserControl in WPF

开发者 https://www.devze.com 2022-12-12 02:25 出处:网络
I have a User Control with a Data Grid inside it which i re-use in a couple of different Pages and am using M-V-VM.

I have a User Control with a Data Grid inside it which i re-use in a couple of different Pages and am using M-V-VM.

How can I / is it possible to expose the Data Grid's SelectedItem dependancy property as a dependancy p开发者_如何学Goroperty on the User Control which contains it???

The goal being that in a Page using the control, i could bind the SelectedItem of the Grid to a property on the Page's view model. I'm not really concerned with changing the SelectedItem from the view model, mostly with having its current value to do some work.


if your goal is just getting your view model to be aware of the selected item you could just use the ItemContainerStyle property. the exmaple below will bind the IsSelected property of the row to the IsSelected property on item the row is displaying. So your view model could have an is selected property for every item in the bound collection and they could tell the parent view model who was selected etc. This will only work if you have SelectionUnit="FullRow", otherwise your selection unit is the cell. in which case you put a style on the cell to select.

<dg:DataGrid 
   ItemsSource="{Binding Path=YourItems}"
   SelectionUnit="FullRow">

   <dg:DataGrid.ItemContainerStyle>
   <Style
      TargetType="{x:Type dg:DataGridRow}">
      <Setter
         Property="IsSelected"
         Value="{Binding IsSelected, Mode=TwoWay}" />
   </Style>
   </dg:DataGrid.ItemContainerStyle>

if its only your view model that needs to know about the selected item you can get around the need for another dependency property this way.

0

精彩评论

暂无评论...
验证码 换一张
取 消