简体   繁体   中英

MVVM WPF Datagrid TemplateColumn Combobox Selected Item Not Working

I am trying to bind some data to a datagrid using the MVVM pattern with WPF. I have confirmed that the datagrid is populating and indeed, that the specific value (Gender) is populated. I've also tried every fix that I could find online (including other questions on this site) that's why I am seeking out an answer here.

<DataGridTemplateColumn Header="Gender" >
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ComboBox ItemsSource="{Binding Genders}"  SelectedItem="{Binding Gender, UpdateSourceTrigger=PropertyChanged}" IsSynchronizedWithCurrentItem="True">
            </ComboBox>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

Things I've tried: Mode=TwoWay, UpdateSourceTrigger=PropertyChanged", IsSynchronizedWithCurrentItem="True". Although, I am not a super experienced WPF and MVVM programmer, so it could be something simple that I just don't know about. My models seem to be working elsewhere and they implement observable/are in observable collections where applicable.

Edit: I got it sorted out. Here is the code that worked for my issue (in case someone else has a similar problem).

<DataGridTemplateColumn Header="Gender" >
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ComboBox ItemsSource="{Binding Path=DataContext.Genders, RelativeSource={RelativeSource FindAncestor, AncestorType = Window}}" SelectedItem="{Binding Gender, UpdateSourceTrigger=PropertyChanged}">
            </ComboBox>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

Assuming you DataGrid's DataContext is the Patient object, try using a RelativeSource binding to point at the DataGrid:

<DataGridTemplateColumn Header="Gender" >
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ComboBox ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGrid}, Path=DataContext.Genders}"
                      SelectedItem="{Binding Gender, UpdateSourceTrigger=PropertyChanged}"
                      IsSynchronizedWithCurrentItem="True">
            </ComboBox>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM