【发布时间】:2020-10-02 14:09:20
【问题描述】:
我遇到了 WPF(c#) 中的绑定问题。
这是我的 xaml:
<my:ComboColumn Header="{Binding PropHeader}"
DataMemberBinding="{Binding Prop}"
ItemsSource="{Binding PossibleProps}"
Width="*"
/>
如果我使用这个绑定:
Binding binding = new Binding()
{
Path = new PropertyPath(nameof(ItemsSource)),
Source = this
};
那么绑定路径是正确的(正在寻找PossibleProps),
但正在寻找虚假的来源。
正在绑定到ViewModel 中的属性PossibleProps。
如果我使用这个绑定:
Binding binding = new Binding()
{
Path = new PropertyPath(nameof(ItemsSource)),
Source = DataContext
};
那么绑定路径为假(正在寻找ItemsSource),
但正在查看我想要的来源。
正在绑定到MainViewModel 中的属性ItemsSource。
你能帮帮我吗?
更新1:
完整代码:
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.GridView;
namespace DB_Admin_WPF.Controls
{
public partial class ComboColumn : GridViewDataColumn
{
public static DependencyProperty ItemsSourceProperty = DependencyProperty.Register("ItemsSource", typeof(IEnumerable<KeyValuePair<Guid?, string>>), typeof(ComboColumn), new PropertyMetadata());
public IEnumerable<KeyValuePair<Guid?, string>> ItemsSource
{
get { return (IEnumerable<KeyValuePair<Guid?, string>>)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
public override FrameworkElement CreateCellElement(GridViewCell cell, object dataItem)
{
var element = new TextBlock();
var valueBinding = new Binding(DataMemberBinding.Path.Path)
{
Mode = BindingMode.TwoWay,
Converter = new ConverterKeyValue()
};
element.SetBinding(TextBlock.TextProperty, valueBinding);
return element;
}
public override FrameworkElement CreateCellEditElement(GridViewCell cell, object dataItem)
{
Binding binding = new Binding()
{
Path = new PropertyPath(nameof(ItemsSource)),
Source = DataContext
};
var element = new RadComboBox();
element.SetBinding(RadComboBox.SelectedItemProperty, DataMemberBinding);
element.DisplayMemberPath = "Value";
element.SetBinding(RadComboBox.ItemsSourceProperty, binding);
return element;
}
//public IEnumerable<KeyValuePair<Guid?, string>> ItemSource { get; set; }
public ComboColumn()
{
InitializeComponent();
}
}
}
更新2
所以我现在确实分享了完整的代码。 xaml 是我想如何使用我的类ComboColumn
DataContext 指的是 MainViewModel,而这指的是 ViewModel,它位于“MainViewModel”的列表中。
在绑定中,我想在MainViewModel处引用PossibleProps。
【问题讨论】:
-
不清楚您要在这里做什么。您已经在 xaml 中创建了绑定,为什么还要在代码中创建绑定?
-
@TimRutter 对不起我的错误解释。我不太习惯用英语写作。我希望你在编辑后明白我的意思。
-
@peni4142:什么是正确的,什么不是?你想从哪里绑定什么属性?
PossibleProps在哪里,你应该如何将ItemsSource属性绑定到这个? -
@mm8 我尝试在
MainViewModel绑定PossibleProps -
@peni4142:从哪里来? XAML 标记?
标签: c# wpf data-binding