简体   繁体   中英

Bind WPF DataGridComboBoxColumn to custom source

I have a View and ViewModel bound to it (WPF/C#).

Now, in DataGrid there is a DataGridComboBoxColumn and I would like set the ItemsSource of the combo to some fixed property of ViewModel. Implicit datacontext of the combo is unfortunatelly the current row.

All I want to do is to "step out" from current row's DataContext.

Thank you for any answer..

What I do is set the window to have the DataContext of your ViewModel then do this:

<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=NodeNames}">
</ComboBox>

This finds the window in the tree and then binds to a property for me called NodeNames.

For example in my project I bind the comboBox to the property from ViewModel in the following way

<ComboBox Name="projectcomboBox" ItemsSource="{Binding Path=Projects}" IsSynchronizedWithCurrentItem="True" DisplayMemberPath="FullName"
              SelectedValuePath="Name"  SelectedIndex="0"  Grid.Row="1" Visibility="Visible" Canvas.Left="10" Canvas.Top="24" Margin="11,6,13,10">
    </ComboBox>

the property is

 public ObservableCollection<Project> Projects
    {
        get { return projects; }
        set
        {
            projects = value;
            RaisePropertyChanged("Projects");
        }
    }

it is important to set the ItemsSource, DisplayMemberPath,SelectedValuePath properties. SelectedIndex you can also bind

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