简体   繁体   中英

Binding Observable Collection from ViewModel to View

I've tried digging through several similar posts and think I'm missing something as I can't get my data to appear. Presently the combobox is empty and I'm hoping that I'm doing something stupid and missing something simple.

Model

public class Rule
{
    [Key]
    public int RuleId { get; set; }
    public string Rule { get; set; }
}

View

<DataGridComboBoxColumn Header="Rule"  DisplayMemberPath="Rule" Width="200">
    <DataGridComboBoxColumn.ElementStyle>
        <Style TargetType="{x:Type ComboBox}">
            <Setter Property="ItemsSource" Value="{Binding Path=_ViewModel.Rules , RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
        </Style>
    </DataGridComboBoxColumn.ElementStyle>
    <DataGridComboBoxColumn.EditingElementStyle>
        <Style TargetType="{x:Type ComboBox}">
            <Setter Property="ItemsSource" Value="{Binding Path=_ViewModel.Rules, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
        </Style>
    </DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>

View cont

public partial class RulePage : Page
{
    private readonly RuleViewModel _ViewModel;
}

ViewModel

public class RuleViewModel
{
    public ObservableCollection<Rule> Rules { get; set; }
}

This is all of the relevant code, I believe. Basically I am trying to get a list of Rules from the Page's _ViewModel instance to load into the combobox but its all blank. Thanks!

Solved it on my own luckily. Turns out since these were Pages, I had to set the {RelativeSource AncestorType={x:Type Window} to {RelativeSource AncestorType={x:Type Page}

I also had to set the DataContext to the Page whenever navigating.

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