【问题标题】:How to bind the property of nested element to the viewmodel property如何将嵌套元素的属性绑定到 viewmodel 属性
【发布时间】:2018-02-07 16:56:45
【问题描述】:

我有如下标记

XAML

    <ComboBox Grid.Row="0" Margin="15,54,352,231" IsSynchronizedWithCurrentItem="True"
                      ItemsSource="{Binding OptimizationTypes}" DisplayMemberPath="TypeName"
                      SelectedIndex="{Binding SelectedIndex, UpdateSourceTrigger=PropertyChanged}">
                <ComboBox.DataContext >
                    <viewModels:MyViewModel />
                </ComboBox.DataContext>
                <ComboBox.ItemContainerStyle>
                    <Style TargetType="{x:Type ComboBoxItem}">
                        <Setter Property="IsEnabled" Value="{Binding IsItemEnabled}" />
                    </Style>
                </ComboBox.ItemContainerStyle>
            </ComboBox>

视图模型

using System.Collections.Specialized;

namespace WpfApplication
{
    public class MyViewModel : INotifyCollectionChanged
    {
        public event NotifyCollectionChangedEventHandler CollectionChanged;
        public bool IsItemEnabled { get; set; }

        public MyViewModel(IBaseControlElement baseControlElement)
        {
            //some code
        }
    }
}

位于我的视图模型上的布尔属性 IsItemEnabled 不适用于此设置器,并且绑定不起作用。据我所知,活页夹试图找到不在 MyViewModel 中的属性。如何解决?我可以只为组合框设置数据上下文,还是在这种情况下还有其他方法?

【问题讨论】:

  • 为什么不能使用带有非无参数构造函数的视图模型作为DataContext?这与您遇到的任何绑定错误有什么关系?
  • 你到底得到了什么错误?我们都不是魔术师,我们只是程序员。
  • "没有无参数构造函数,因此不能作为数据上下文" -- 不成立。拥有无参数构造函数不是成为DataContext 值的先决条件。实际上,在ComboBox 中,一个视图模型对象通常是在代码隐藏中创建的,而不是在 XAML 中创建的,并且将参数传递给构造函数是微不足道的。无论您的代码中发生了什么,都不是因为该对象没有无参数构造函数。请解决您的问题。对于初学者,请参阅 minimal reproducible exampleHow to Ask
  • 只是工具提示:MyViewModel 类型不包含任何可访问的构造函数
  • 对不起。我已经改变了我的问题。让我们忘记 datacontext 和我对此的结论。无论如何,该怎么做

标签: c# wpf mvvm


【解决方案1】:

试试

<Setter Property="IsEnabled" Value="{Binding Path=DataContext.IsItemEnabled,RelativeSource={RelativeSource AncestorType=ComboBox}}" />

【讨论】:

  • 我得到了带有文本的新工具提示:无法在对象类型的数据上下文中解析属性 IsItemEnabled。我应该在哪里以及如何设置数据上下文?
  • 我想我是根据你写的假设,但你的 MyViewModel 有一个 public bool IsItemEnabled { get;放; } 或类似的东西?
  • 是的,它有这个属性
  • 确切的错误是什么? VS中的输出窗口应该会输出错误。
  • System.Windows.Data 错误:40:BindingExpression 路径错误:在“对象”“OptimizeType”(HashCode=42284632)上找不到“IsItemEnabled”属性。绑定表达式:路径=IsItemEnabled; DataItem='OptimizeType' (HashCode=42284632);目标元素是'ComboBoxItem'(名称='');目标属性是“IsEnabled”(类型“布尔”)
猜你喜欢
  • 2011-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-03
  • 2020-07-07
  • 1970-01-01
  • 2017-08-08
  • 2015-01-25
相关资源
最近更新 更多