问题
For an application I need to create a DataGrid with a DataGridTextColumn which has MultiBinding.
The first Binding uses a property given in the ItemsSource, the second Binding should use a Property from my ViewModel.
<DataGridTextColumn Header="Hourly wage" SortMemberPath="HourlyWage">
<DataGridTextColumn.Binding>
<MultiBinding StringFormat="{}{0}{1}">
<Binding Path="HourlyWage" />
<Binding Path="CurrencyUnit" />
</MultiBinding>
</DataGridTextColumn.Binding>
</DataGridTextColumn>
In that case HourlyWage is a property of the current item. CurrencyUnit is a property in my ViewModel.
If I start my application this column is empty. So how do I get it displaying both?
I'm using Catel as my MVVM Framework and MahApps.Metro for my GUI. I can't create a ViewModel in my View as it is handled by Catel.
Regards, Stefan
回答1:
If you cannot access the view model, you can define the second binding as follows:
<Binding RelativeSource="{RelativeSource AncestorType=DataGrid}"
Path="DataContext.CurrencyUnit" />
The source of the Binding will be set to the DataGrid instance. The path DataContext.CurrencyUnit will refer to the property YourViewModel.CurrencyUnit, assuming that your view model holds the items collection for the data grid and the currency unit property.
回答2:
You can set the Binding Source for the second binding to your view model instance. I used the following View Model:
namespace WpfApplication1
{
public class ViewModel
{
public ViewModel()
{
this.items = new List<Item> {
new Item("13.4"),
new Item("22.3")};
}
public List<Item> Items
{
get { return this.items; }
}
public string CurrencyUnit
{
get { return "$"; }
}
private List<Item> items;
}
}
And the Item class as follows:
namespace WpfApplication1
{
public class Item
{
public Item(string hWage)
{
HourlyWage = hWage;
}
public string HourlyWage { get; set; }
}
}
Then I used the following XAML:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:ViewModel x:Key="viewModel" />
</Window.Resources>
<Grid DataContext="{StaticResource viewModel}">
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Items}">
<DataGrid.Columns>
<DataGridTextColumn Header="Hourly wage"
SortMemberPath="HourlyWage">
<DataGridTextColumn.Binding>
<MultiBinding StringFormat="{}{0}{1}">
<Binding Path="HourlyWage" />
<Binding Source="{StaticResource viewModel}"
Path="CurrencyUnit" />
</MultiBinding>
</DataGridTextColumn.Binding>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
来源:https://stackoverflow.com/questions/20819168/binding-viewmodel-property-in-datagridtextcolumn