开发者

Silverlight - bind from DataGrid column back to root property of view model?

开发者 https://www.devze.com 2023-01-24 19:50 出处:网络
I have the following XAML: <UserControl.Resources> <local:MainPageViewModel x:Key=\"ViewModel\" />

I have the following XAML:

<UserControl.Resources>
    <local:MainPageViewModel x:Key="ViewModel" />
</UserControl.Resources>

<Grid x:Name="LayoutRoot" 
      DataContext="{Binding Source={StaticResource ViewModel}}">
    <sdk:DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Items}">
        <sdk:DataGrid.Columns>
            <sdk:DataGridTextColumn Header="ID" Binding="{Binding ID}" />
            <sdk:DataGridTextColumn Header="Name" Binding="{Binding Name}" />
            <sdk:DataGridCheckBoxColumn
                Header="Checkbox Column"
                Binding="{Binding Source={StaticResource ViewModel},
                                  Path=SomeBooleanProperty}"/>

        </sdk:DataGrid.Columns>
    </sdk:DataGrid>
</Grid>

So, basically I want to have one of the columns (the checkbox column) bound to some property (SomeBooleanProperty) that is directly on the ViewModel, as opposed to a property on one of the items in the Items collection. (Yes this is a bit contrived, but it gets to my problem.) The problem is that based on my testing, if you bind via the StaticResource, it seems like the value isn't updated based on INotifyPropertyChanged event firing. The initial value is correct, but it never changes. I can't figure out another way to get "out" of the Items binding and back up to the ViewModel, from within a column binding.

I think that in WPF you could do this with a RelativeB开发者_Python百科inding using FindAncestor. But that functionality doesn't exist in Silverlight. Are there other ways to accomplish this?


Element binding is not limited to "controls". You could try element binding to the LayoutRoot as that is resolved at runtime based simply on names in the current scope.

It should then pickup the DataContext of whatever element you point it at.

e.g.

<sdk:DataGridCheckBoxColumn
                Header="Checkbox Column"
                Binding="{Binding ElementName=LayoutRoot,
                                  Path=SomeBooleanProperty}"/>

If the binding still does not fire it will be a feature/flaw of the of the CheckBoxColumn (e.g. it picks up values from the row data context)


I really don't know what happened. Based on @TerenceJackson's comment saying that it worked for him, I completely rebuilt the page in question and the VM code, and everything worked. I looked with a very critical eye at both pieces of code to figure out what was different, but I couldn't. So although it bugs me, I'm going to have to move on. I think I'm going to leave this question around on the off chance that someone has the same problem and actually figures out what the cause was.

0

精彩评论

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