绑定到包含ComboBox的DataGridTemplateColumn

时间:2013-12-10 01:24:26

标签: c# wpf combobox

我需要将一个DataColumn绑定到表示ComboBox的SeletectedItem的对象,该对象位于DataGridTemplateColumn中。我几乎尝试了所有东西,但是我只能绑定到另一个专栏的标题。

XAML看起来像这样:

 <DataGrid.Columns>
    <DataGridTemplateColumn x:Name="MealPartsColumn" Header="Składniki">
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <ComboBox x:Name="MealPartsComboBox" ItemsSource="{Binding MealParts}" SelectedIndex="0" SelectedValuePath="{Binding FoodQuantity}">
                    <ComboBox.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Path=FoodProduct.ProductName}" Width="100"/>
                        </DataTemplate>
                    </ComboBox.ItemTemplate>
                </ComboBox>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
    <DataGridTextColumn Binding="{Binding ElementName=MealPartsComboBox, Path=SeletectedItem.FoodQuantity}" ClipboardContentBinding="{x:Null}" Header="Ilość w gramach" Width="100"/>
</DataGrid.Columns>

我的模型描述的是:

public class Meal
{
    public List<MealPart> MealParts { get;set; }
}

public class MealParts
{
    public float FoodQuantity {get;set;}
    public FoodProduct FoodProduct {get;set;}
}

public class FoodProduct 
{
    public string ProductName {get;set;}
}

相关的后端代码:

Meals = new ObservableCollection<Meal>(mealsForDay);
HistoryDataGrid.ItemsSource = Meals;

ComboBox中的ProductName正确填充,但是,我无法将其绑定到TextColumn。

这是我制作的最终有效的代码。我需要为该解决方案明确设置UpdateSourceTrigger才能工作。

<DataGridTemplateColumn x:Name="MealPartsColumn" Header="Składniki">
                            <DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <ComboBox x:Name="MealPartsComboBox" DisplayMemberPath="FoodProduct.ProductName" ItemsSource="{Binding MealParts}" SelectedItem="{Binding SelectedMealPart, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}"/>
                                </DataTemplate>
                            </DataGridTemplateColumn.CellTemplate>
                        </DataGridTemplateColumn>
                        <DataGridTextColumn Header="Ilość w gramach" Binding="{Binding SelectedMealPart.FoodQuantity, UpdateSourceTrigger=PropertyChanged}" />

1 个答案:

答案 0 :(得分:0)

我认为您应该通过Meal

上的属性绑定来实现此目的
public class Meal : INotifyPropertyChanged
{
    public List<MealPart> MealParts { get;set; }
    public MealPart SelectedMealPart {
        get { return _selected;  }
        set { _selected = value;
             // Implement INotifyPropertyChanged and fire the event here
        }
    }
}

您需要实现INotifyPropertyChanged才能使绑定正确更新。

然后:

<ComboBox ... SelectedItem={Binding SelectedMealPart}" ...>

<DataGridTextColumn Binding="{Binding SelectedMealPart.FoodQuantity}" ...>