【问题标题】:wpf combobox not binding to collection when inside ContentTemplate在 ContentTemplate 内时,wpf 组合框未绑定到集合
【发布时间】:2018-11-06 18:39:28
【问题描述】:

我正在尝试基于属性(组合框或文本框)显示某个控件。所以我实现了这个内容控制:

   <!--<ComboBox MaxWidth="200" Background="#333333" ItemsSource="{Binding ModelObjectWrapper.Values}" Grid.Row="1" Grid.Column="1"/>-->
    <ContentControl Grid.Row="1" Grid.Column="1">
        <ContentControl.Resources>
            <Style TargetType="ContentControl">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ModelObjectWrapper.ObjType}" Value="typeA">
                        <Setter Property="ContentTemplate">
                            <Setter.Value>
                                <DataTemplate>
                                    <ComboBox HorizontalAlignment="Left" MaxWidth="200" Background="#333333" ItemsSource="{Binding ModelObjectWrapper.Values, UpdateSourceTrigger=PropertyChanged}"/>
                                </DataTemplate>
                            </Setter.Value>
                        </Setter>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding ModelObjectWrapper.ObjType}" Value="typeB">
                        <Setter Property="ContentTemplate">
                            <Setter.Value>
                                <DataTemplate>
                                    <TextBox />
                                </DataTemplate>
                            </Setter.Value>
                        </Setter>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </ContentControl.Resources>
    </ContentControl>

问题是组合框在它是控件模板的一部分时没有显示任何项目,而且我知道绑定列表确实有它们,所以我假设组合框没有正确绑定到ItemsSource。 注释掉的第一行(只有一个没有模板的组合框)可以正常工作。我没有做正确的绑定吗?难道是因为它是数据触发器的一部分,它没有得到正确的DataContext?我必须注意DataTrigger 本身效果很好(如果*.ObjType == "typeA",IE 会显示一个组合框。

VM 是一个对象的包装类:

public class ModelObjectWrapper : ViewModelBase
{
private theModelObject model_obj;

public ModelObjectWrapper(theModelObject obj)
{
    model_obj = obj;
}       

public ObservableCollection<string> Values
{
    get { return model_obj.Values; }
    set
    {
        if (value == model_obj.Values)
            return;

        model_obj.Values = value;
        OnPropertyChanged();
    }
}
}

【问题讨论】:

    标签: wpf combobox contentcontrol


    【解决方案1】:

    ContentControl 中根元素的DataContext 是同一ContentControlContent。尝试使用RelativeSource 绑定到ContentControlDataContext 的属性:

    <ComboBox HorizontalAlignment="Left" MaxWidth="200" Background="#333333" 
              ItemsSource="{Binding DataContext.ModelObjectWrapper.Values, RelativeSource={RelativeSource AncestorType=ContentControl}}"/>
    

    顺便说一句,将ItemsSource 绑定的UpdateSourceTrigger 设置为PropertyChanged 是没有意义的,因为ComboBox 从不设置源属性。

    【讨论】:

    • 感谢 mm8 的解决方案和解释。完美运行!
    猜你喜欢
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 1970-01-01
    • 2016-12-10
    • 2017-04-14
    • 1970-01-01
    相关资源
    最近更新 更多