gpt4 book ai didi

c# - 将 WPF DatagridComboBoxColumns 数据绑定(bind)到 MVVM 不起作用

转载 作者:行者123 更新时间:2023-12-03 10:49:08 29 4
gpt4 key购买 nike

按照这2个答案:

Using WPF DataGridComboBoxColumn with MVVM - Binding to Property in ViewModel

Binding a WPF DataGridComboBoxColumn with MVVM

1) 在组合框中进行选择时,我无法设置 ObservableCollections 中的值。

组合框正在使用 ViewModel 中的列表填充,但未设置值。

代码:

<DataGrid ItemsSource="{Binding SidValues1through5, Mode=TwoWay}"                                  
AutoGenerateColumns="False"
Grid.Row="1"
Margin="5"
VerticalAlignment="Top"
HorizontalAlignment="Center">
<DataGrid.Columns>
<DataGridComboBoxColumn Header="1"
Width="100"
SelectedValueBinding="{Binding Value1}"
SelectedValuePath="Value1">
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource"
Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.AvailableSids}" />
</Style>
</DataGridComboBoxColumn.ElementStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource"
Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.AvailableSids}" />
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>

ViewModel 接口(interface)(我已经调试过并且连接到 ViewModel, View 上的其他控件都绑定(bind)正确:

ETA:BindableCollection 继承自 ObservableCollection,它是一个 Caliburn.Micro 类型。
public interface ICustomSIDViewModel : IScreen
{
BindableCollection<SidValues> SidValues1through5 { get; set; }
BindableCollection<SidValues> SidValues6through10 { get; set; }

IList<string> AvailableSids { get; }
}

public class SidValues
{
public string Value1 { get; set; }
public string Value2 { get; set; }
public string Value3 { get; set; }
public string Value4 { get; set; }
public string Value5 { get; set; }
}

2) 一旦我解决了这个问题,有没有一种更简洁的方法让所有列都继承这一组 DataGridComboBoxColumn.ElementStyle 和 DataGridComboBoxColumn.EditingElementStyle?

我问的原因是有 10 列都有相同的组合框列表。

最佳答案

对于第一个问题 - 它是 WPF,因此您不需要在绑定(bind)上使用 Mode=TwoWay,但为了以防万一,请尝试对初学者使用。

WPF afaik 的默认值是 TwoWay,但不是 SL。还是试试吧。

对于第二个问题,只需在资源字典中声明一个嵌套样式。嵌套样式适用于目标控件的子元素

例如

<Style x:Key="DataGridComboBoxStyle" TargetType="DataGrid">
<!-- Nested -->
<Style.Resources>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.AvailableSids}" />
</Style>
</Style.Resources>
</Style>

您还可以将样式应用于整个控件并将此样式嵌套在该样式中:)

关于c# - 将 WPF DatagridComboBoxColumns 数据绑定(bind)到 MVVM 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11906115/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com