Binding to property of datacontext parent- WPF - wpf

I have a DataGrid:
<DataGrid x:Name="DG" ItemsSource="{Binding}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="?" Binding="{Binding l}">
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
In DataContext of the DataGrid there is the collection of class X:
public ObservableCollection<xxx> col{ get; set; }// = DataContext of DG
private string lName;
public string LName
{
get { return lName; }
set
{
lName= value;
NotifyPropertyChanged("LName");
}
}
I want lName will be the header of a particular column in DataGrid
I try this way:
<DataGridTextColumn Binding="{Binding l}">//l=prop of xxx class that contains the collection
<DataGridTextColumn.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding DataContext.LName,
RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
</DataTemplate>
</DataGridTextColumn.HeaderTemplate>
</DataGridTextColumn>
It did not work
how can do this?

Try {Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.LName}
Also I wouldn't play with name cases. WPF is pretty case-sensivity. Avoid of using one-symbol names

Binding paths are also case-sensitive. There is no property lName in your DC.

Related

Accessing a combo box property inside a datagrid in wpf

I have a datagrid which has four columns of combobox in wpf. At the starting, the first combobox is enabled. After making a selection on the first combobox, the second combobox gets enabled. I am unable to access the combobox name property in my xaml.cs file so that I can enable the next combobox column after successful selection of the first one. Can you suggest how to access the combobox property which is present inside a datagrid in my xaml.cs file ?
This is my xaml code
<DataGridTemplateColumn
Header ="Example 9">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding PartIds, RelativeSource={RelativeSource AncestorType=Window}}" SelectedItem ="{Binding PartId,UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
Assuming you have two columns in your DataGrid, the first column contains a combobox, and its selecteditem is bound to a property named PartId, the second column contains also a combobox with a selecteditem bound to a property named PartId2, your model should look something like that:
public class Model
{
public string PartId { get; set; }
public string PartId2 { get; set; }
}
Now, assuming your DataGrid's itemsource is bound to an ObservableCollection named DgCollection:
private ObservableCollection<Model> _dgCollection;
public ObservableCollection<Model> DgCollection
{
get { return _dgCollection; }
set
{
if (Equals(value, _dgCollection)) return;
_dgCollection = value;
OnPropertyChanged();
}
}
The second column could use a DataTrigger to activate its combobox once the selecteditem of the first column is set, like so:
<DataGrid ItemsSource="{Binding DgCollection}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn
Header ="Example 9">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding PartIds, RelativeSource={RelativeSource AncestorType=Window}}" SelectedItem ="{Binding PartId,UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn
Header ="Example 10">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox x:Name="FirstCbx" ItemsSource="{Binding PartIds, RelativeSource={RelativeSource AncestorType=Window}}" SelectedItem ="{Binding PartId2,UpdateSourceTrigger=PropertyChanged}" >
<ComboBox.Style>
<Style TargetType="ComboBox">
<Setter Property="IsEnabled" Value="True"/>
<Style.Triggers>
<DataTrigger Binding="{Binding PartId}" Value="{x:Null}">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ComboBox.Style>
</ComboBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
You could generalize this to four columns easily.

WPF MVVM Databinding Nested Datagrid

I'm a beginner to WPF and MVVM pattern. I still have a issue with databinding in case of backward binding. I would like to bind selectedValues of the Comboboxes into my Oberservable Collection. I learned is possible to bind the value of a combobox to a property, but in this case I would like to bind to a property of a collection and the collection is the parent.
Could somebody explain me how to bind the combobox selectedvalues to my observablecollection?
I have a workaround in my mind to make for each combobox a new property in my viewmodel and collect all values and store by button press this values into my collection, but this seems for me wrong, because is not the behavouir of databinding.
EDIT The comboboxes items are corrected populated from each model, but how i can bind the selectedvalue of the combobox to my collection property?
<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type Window}},
Path=DataContext.Cities}"
DisplayMemberPath="Name"
SelectedValue="{Binding Path=RowEntries }"/>
The SelectedValue="{Binding Path=RowEntries}" is wrong or is this correct?
EDIT 2
I added a Listview binded to my collection to see, if the properties are binded to the selectedvalue of my combobox, but is keeps empty.
<ListView ItemsSource="{Binding RowEntries}" BorderBrush="Black" BorderThickness="1">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=CityName}"></TextBlock>
<TextBlock Text="{Binding Path=CountryName}"></TextBlock>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
I have this solution:
My Models:
// INPC implemented by Propertychanged.Fody
public class RowEntry : BaseModel
{
public string CityName { get; set; }
public string CountryName { get; set; }
}
// INPC implemented by Propertychanged.Fody
public class City : BaseModel
{
public string Name { get; set; }
}
// INPC implemented by Propertychanged.Fody
public class Country : BaseModel
{
public string Name { get; set; }
}
My ViewModel:
public class TestViewModel : ViewModelBase
{
#region properties
// INPC implemented by Propertychanged.Fody
public ObservableCollection<City> Cities { get; set; } = new ObservableCollection<City>();
public ObservableCollection<Country> Countries { get; set; } = new ObservableCollection<Country>();
public ObservableCollection<RowEntry> RowEntries { get; set; } = new ObservableCollection<RowEntry>();
#endregion
#region constructors and destructors
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public TestViewModel()
{
// Sample Data
var temp = new City { Name = "Rom" };
Cities.Add(temp);
var temp2 = new City { Name = "Sydney" };
Cities.Add(temp2);
var temp3 = new Country { Name = "Italy" };
Countries.Add(temp3);
var temp4 = new Country { Name = "Australia" };
Countries.Add(temp4);
RowEntries.Add(new RowEntry());
}
#endregion
}
My Ui:
<StackPanel>
<DataGrid ItemsSource="{Binding RowEntries}" AlternationCount="{Binding Items.Count, RelativeSource={RelativeSource Self}}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding AlternationIndex, RelativeSource={RelativeSource AncestorType=DataGridRow}}" Header="#"/>
<DataGridTemplateColumn Header="City">
<DataGridTemplateColumn.CellTemplate>
<HierarchicalDataTemplate>
<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type Window}},
Path=DataContext.Cities}"
DisplayMemberPath="Name"
SelectedValue="{Binding Path=RowEntries }"/>
</HierarchicalDataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Countries">
<DataGridTemplateColumn.CellTemplate>
<HierarchicalDataTemplate>
<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type Window}},
Path=DataContext.Countries}"
DisplayMemberPath="Name"/>
</HierarchicalDataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
<Button Content="Add Row" Margin="0,0,1797,0"></Button>
</StackPanel>
You should bind the SelectedValue property of the ComboBoxes to the CityName and CountryName properties of the RowEntry object and set the SelectedValuePath property of the ComboBoxes to "Name". Also set the UpdateSourcePropertyTrigger of the bindings to PropertyChanged:
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding AlternationIndex, RelativeSource={RelativeSource AncestorType=DataGridRow}}" Header="#"/>
<DataGridTemplateColumn Header="City">
<DataGridTemplateColumn.CellTemplate>
<HierarchicalDataTemplate>
<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.Cities}"
DisplayMemberPath="Name"
SelectedValuePath="Name"
SelectedValue="{Binding Path=CityName, UpdateSourceTrigger=PropertyChanged}"/>
</HierarchicalDataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Countries">
<DataGridTemplateColumn.CellTemplate>
<HierarchicalDataTemplate>
<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.Countries}"
DisplayMemberPath="Name"
SelectedValuePath="Name"
SelectedValue="{Binding Path=CountryName, UpdateSourceTrigger=PropertyChanged}"/>
</HierarchicalDataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
Then the setters of the source properties (CityName and CountryName) will be called when you select an item in the ComboBoxes.
If you want to select some values initially, you simply set these properties to some values that are present in the ComboBoxes:
public TestViewModel()
{
...
RowEntries.Add(new RowEntry() { CityName = "Sydney", CountryName = "Australia" });
}

wpf datagridcombobox linq foreign key

I have searched all over and keep finding similar examples that are not working for me. Can someone point out where I am messing up?
I have two tables AlarmName and AlarmLevel. Linked by a foreign key AlarmName.AlarmLevelID -> AlarmLevel.Id.
I have the following in my XAML:
<DataGrid Name="Alarms" AutoGenerateColumns="false">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}" Header="Name" Width="75" />
<DataGridTextColumn Binding="{Binding Description}" Header="Description" />
<DataGridTextColumn Binding="{Binding AlarmLevel.Name}" Header="AName" Width="75"/>
<DataGridTemplateColumn Header="Alarm Level">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding DataContext.AlarmLevel, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
DisplayMemberPath="Name"
SelectedValuePath="AlarmLevelID"
SelectedValue="{Binding Id}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
And the following in my code behind:
UISimulation1.Data.UISimulationDBDataContext db = new UISimulation1.Data.UISimulationDBDataContext();
var alarm = (from v in db.AlarmNames
select v);
Alarms.ItemsSource = alarm;
The DataGridTextColumns work and pull the right data. However, I can not make the combobox work or display anything no matter what I try.
Clearly, I am missing something obvious; but have tried 50 variants of the combobox based on google examples with zero results.
--rt
You need to expose the records in the AlarmLevel table using a public property that you bind the ItemsSource property of the ComboBox to. Please refer to the following sample code.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
using (UISimulation1.Data.UISimulationDBDataContext db = new UISimulation1.Data.UISimulationDBDataContext())
{
AlarmNames = (from v in db.AlarmNames
select v).ToList();
AlarmLevels = (from v in db.AlarmLevels
select v).ToList();
}
}
public IEnumerable AlarmNames { get; private set; }
public IEnumerable AlarmLevels { get; private set; }
}
<DataGrid Name="Alarms" ItemsSource="{Binding AlarmNames}" AutoGenerateColumns="false">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}" Header="Name" Width="75" />
<DataGridTextColumn Binding="{Binding Description}" Header="Description" />
<DataGridTextColumn Binding="{Binding AlarmLevel.Name}" Header="AName" Width="75"/>
<DataGridTemplateColumn Header="Alarm Level">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding DataContext.AlarmLevels, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
DisplayMemberPath="Name"
SelectedValuePath="AlarmLevelID"
SelectedValue="{Binding Id}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
The DataGrid columns don’t belong to the visual or logical tree of the DataGrid, see this

How to implement editable DataGridComboBoxColumn in WPF DataGrid

I want to enable the user to edit some data in WPF DataGrid ( from the .net Framework 4.0). The "instruments" column should allow the user to select an available intrument from a static list or to write a free text.
My DataGrid is binded to data using MVVM. I've tried many solutions I've found in internet but none of them work correctly.
Here is my code:
<DataGrid Margin="0,6" ItemsSource="{Binding Path=Orders}" AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" CanUserResizeRows="True">
<DataGrid.Columns>
<DataGridComboBoxColumn Header="Instrument" MinWidth="140"
ItemsSource="{x:Static ViewModel.Instruments}" SelectedItemBinding="{Binding Path=SelectedInstrument}">
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="ComboBox">
<Setter Property="IsEditable" Value="True"/>
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
</DataGrid.Columns>
</DataGrid>
The drop-down-list is shown correctly. The field can be edited with any text, but it sets a null to the SelectedInstrument after the drop-down is closed for the free text. It works only for the selected item. I've tried to change to SelectedValueBinding, but it doesn't help.
How to implement this requirements properly? Can someone post here a working sample?
Additional:
Orders is ObservableCollection
Order has Property like string Title, DateTime Ordered, string SelectedInstrument,
Instruments is a string[]
Solutions:
Following suggest as a workaround from bathineni works:
<DataGrid Margin="0,6" ItemsSource="{Binding Path=Orders}" AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" CanUserResizeRows="True">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Instrument" MinWidth="140">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=SelectedInstrument, Mode=OneWay}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox IsEditable="True" Text="{Binding Path=SelectedInstrument}"
ItemsSource="{x:Static ViewModel.Instruments}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
this is happening because the free text which is enter is of type string and selected item what you have binded to the comboBox is of some complex type....
instead of using DataGridComboBoxColumn use DataGridTemplateColumn and you can bind Text property of the comboBox to some property which will hold the free text value after closing drop down list.
you can get better idea by looking at the following sample.
<DataGrid>
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox IsEditable="True"
Text="{Binding NewItem}"
ItemsSource="{Binding Sourcelist.Files}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Try to use SelectedValue only but along with it use DisplayMemberPath and TextSearch.TextPath.
<ComboBox IsEditable="True" DisplayMemberPath="MyDisplayProperty" SelectedValuePath="MyValueProperty" SelectedValue="{Binding MyViewModelValueProperty}" TextSearch.TextPath="MyDisplayProperty" />
For editable comboboxes we must synchronize what value the combo selects, what value the items display and what value we must search based on user input.
But If you are using a string collection to bind your combobox then you can try following...
Add a new property in your ViewModel called InstrumentsView. This returns a new ListCollectionView.
public static string ListCollectionView InstrumentsView
{
get
{
return new ListCollectionView(Instruments);
}
}
Change your DataGridComboBoxColumn XAML as below...
<DataGridComboBoxColumn Header="Instrument" MinWidth="140"
ItemsSource="{x:Static ViewModel.InstrumentsView}">
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="ComboBox">
<Setter Property="IsEditable" Value="True"/>
<Setter Property="IsSynchronizedWithCurrentItem" Value=True" />
<Setter Property="SelectedItem" Value="{Binding SelectedInstrument, Mode=OneWayToSource}" /> <!-- Assuming that SelectedInstrument is string -->
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
Tell me if this works....
You can create your own ComboBox column type by subclassing DataGridBoundColumn. Compared to bathineni's solution of subclassing DataGridTemplateColumn the below solution has the benefit of better user experience (no double-tabbing) and you have more options to tune the column to your specific needs.
public class DataGridComboBoxColumn : DataGridBoundColumn {
public Binding ItemsSourceBinding { get; set; }
protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) {
var textBox = new TextBlock();
BindingOperations.SetBinding(textBox, TextBlock.TextProperty, Binding);
return textBox;
}
protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) {
var comboBox = new ComboBox { IsEditable = true };
BindingOperations.SetBinding(comboBox, ComboBox.TextProperty, Binding);
BindingOperations.SetBinding(comboBox, ComboBox.ItemsSourceProperty, ItemsSourceBinding);
return comboBox;
}
protected override object PrepareCellForEdit(FrameworkElement editingElement, RoutedEventArgs editingEventArgs) {
var comboBox = editingElement as ComboBox;
if (comboBox == null) return null;
comboBox.Focus(); // This solves the double-tabbing problem that Nick mentioned.
return comboBox.Text;
}
}
You can then use the component for example like this.
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding MyItems}">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
<local:DataGridComboBoxColumn Header="Thingy" Binding="{Binding Thingy}"
ItemsSourceBinding="{Binding
RelativeSource={RelativeSource AncestorType={x:Type local:MainWindow}},
Path=Thingies}"/>
</DataGrid.Columns>
</DataGrid>
I got this solution by following this answer to a similar question.
Maybe it'll still be useful to someone. This solution allows to add new entered values to selection list and has no side effects while editing.
XAML:
<DataGridTemplateColumn Header="MyHeader" Width="Auto">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox IsEditable="True"
Text="{Binding MyTextProperty, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
DisplayMemberPath="MyTextProperty"
SelectedValuePath="MyTextProperty"
ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=DataContext.SelectionList}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
ViewModel:
public class MyViewModel
{
public class MyItem : INotifyPropertyChanged {
private string myTextProperty;
public string MyTextProperty {
get { return myTextProperty; }
set { myTextProperty = value;
OnPropertyChanged("MyTextProperty"); }
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName]string prop = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
}
}
public ObservableCollection<MyItem> MyItems { get; set; }
public object SelectionList { get; set; }
}
CodeBehinde:
MyWindow.DataContext = MyViewModelInstance;
MyDataGrid.ItemsSource = MyItems;
// Before DataGrid loading and each time after new MyProperty value adding, you must execute:
MyViewModelInstance.SelectionList = MyViewModelInstance.MyItems.OrderBy(p => p.MyTextProperty).GroupBy(p => p.MyTextProperty).ToList();

Bind linq to DataGridComboBoxColumn

I am using wpftoolkit from wpf.codeplex.com . While binding a data table(through linq object list) there is a collumn that contains a reference of another table content as a foreign key. So, generally, currently, on that column in datagrid, i want to show a combo box containing the element of another table and selelted item should be from my concerned table. Here is what I am writing:
<dg:DataGrid x:Name="UsersGrid" AutoGenerateColumns="False" CellEditEnding="UsersGrid_CellEditEnding" RowEditEnding="UsersGrid_RowEditEnding" PreviewKeyDown="UsersGrid_PreviewKeyDown">
<dg:DataGrid.Columns>
<dg:DataGridTextColumn Binding="{Binding Path=Id}" Header="Id" Visibility="Hidden" />
<dg:DataGridTextColumn Binding="{Binding Path=Username}" Header="User Name" />
<dg:DataGridTextColumn Binding="{Binding Path=Password}" Header="Password" />
<dg:DataGridTextColumn Binding="{Binding Path=RoleId}" Header="Role ID" />
<dg:DataGridComboBoxColumn x:Name="Roles" ItemsSource="{Binding Path=TVRole}">
</dg:DataGridTemplateColumn>
</dg:DataGrid.Columns>
</dg:DataGrid>
For making the binding, the code behind file contains as the following code:
UsersGrid.ItemsSource = UserManager.GetAllUsers();
Problem is that, I am now don't know what to place in the "ItemsSource" property to achieve what i want for the DataGridComboBoxColumn column . Can anyone please help me? Again mentioning, i want to bind it with linq object.
There is a strange bug with a DataGridComboBoxColumn: the ItemsSource property doesn't support advanced bindings. But you can use DataGridTemplateColumn, and code will be like this:
<DataGrid ItemsSource="{Binding Users}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=Id}" Header="Id" Visibility="Hidden" />
<DataGridTextColumn Binding="{Binding Path=Username}" Header="User Name" />
<DataGridTextColumn Binding="{Binding Path=Password}" Header="Password" />
<DataGridTextColumn Binding="{Binding Path=RoleId}" Header="Role ID" />
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding Path=DataContext.Roles, RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}}"
DisplayMemberPath="Title" SelectedValuePath="Id" SelectedValue="{Binding RoleId, Mode=TwoWay}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
And add this code to the constructor of the View:
var model = new MainViewModel() { Users = UserManager.GetAllUsers(), Roles = UserManager.GetAllRoles() };
this.DataContext = model;
Where the MainViewModel is an auxiliary class:
public class MainViewModel
{
public List<Role> Roles { get; set; }
public List<User> Users { get; set; }
}
Another way is using a list of UserViewModel instead of a list of User, where each viewmodel class contains the list of roles, so it will be possible to use a correct binding. But it is a more complicated solution than above-mentioned one.

Resources