C#/WPF: Binding Combobox ItemSource in Datagrid to element outside of the DataContext

前端 未结 2 1613
轻奢々
轻奢々 2021-02-07 17:25

I\'d like to do following:

public List PreLoadedUserList { get; set; }
public List SomeDataRowList { get; set; }

public class Use         


        
相关标签:
2条回答
  • 2021-02-07 17:57

    If RowEntries is a custom class, just give it a reference to the PreLoadedUserList. Then, each instance has a pointer to it and you can use it in your binding.

    Just a suggestion, class names like Users and RowEntries suggest that they are collections but your usage looks like they're the item not the collection. I'd use singular names to avoid any confusion. I'd do something like this

    public List<User> PreLoadedUserList { get; set; }
    public List<RowEntry> SomeDataRowList { get; set; }
    
    public class User
    {
        public int Age { get; set; }
        public string Name { get; set; }
    }
    public class RowEntry 
    {
        public int UserAge { get; set; }
        public List<User> PreLoadedUserList { get; set; }
    }
    
    // at the point where both PreLoadedUserList is instantiated
    // and SomeDataRowList is populated
    SomeDataRowList.ForEach(row => row.PreLoadedUserList = PreLoadedUserList);
    
    0 讨论(0)
  • 2021-02-07 17:59

    Here we go :-)

    <my:DataGridTemplateColumn Header="SomeHeader">
        <my:DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <ComboBox SelectedValuePath="UserAge" 
                    SelectedValue="{Binding Age}" 
                    DisplayMemberPath="Name" 
                    ItemsSource="{Binding Path=DataContext.PreLoadedUserList, 
                        RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" 
                    IsReadOnly="True" Background="White" />
            </DataTemplate>
        </my:DataGridTemplateColumn.CellTemplate>
    </my:DataGridTemplateColumn>
    

    Hope this can help someone else too.

    Cheers

    0 讨论(0)
提交回复
热议问题