【问题标题】:Combobox binding not working when window is in grid container当窗口位于网格容器中时,组合框绑定不起作用
【发布时间】:2013-08-15 15:58:43
【问题描述】:

我尝试使用此代码在ComboBox 中绑定一个列表:

var template = new DataTemplate();
var comboBoxFactory = new FrameworkElementFactory(typeof(ComboBox));
template.VisualTree = comboBoxFactory;
Binding b = new Binding();
b.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, this.GetType(), 1);
b.Path = new PropertyPath("DataContext");
comboBoxFactory.SetBinding(ComboBox.ItemsSourceProperty, b);
comboBoxFactory.SetBinding(ComboBox.SelectedItemProperty, new Binding("ClassRoom"));

当我简单地启动窗口时它正在工作,如下所示:

winListOrgane ee = new winListOrgane();
ee.Show();

但是当我尝试将此窗口放入网格容器中时,它不起作用:

_currentWindow = (ModelPage)Activator.CreateInstance(pPage.GetType());
_currentWindow.SetParam(genParam);
_currentWindow.InitPage();

object content = _currentWindow.Content;
_currentWindow.Content = null;
_containerPage.Children.Add((UIElement)content);

我可以做些什么来解决这个问题?

谢谢

最好的问候, 弗雷德里克

【问题讨论】:

    标签: wpf binding combobox window


    【解决方案1】:

    看起来这是您在Binding 上的RelativeSource。由于您绑定到特定的 Window 类 - 在这种情况下,看起来 GetType() 将返回 typeof(winListOrgane)。如果你把它改成typeof(Window),它应该可以工作:

    b.RelativeSource = 
        new RelativeSource(RelativeSourceMode.FindAncestor, typeof(Window), 1);
    

    【讨论】:

    • 事实上,这个组合框在我的数据网格的一列中,并且这个数据网格的数据上下文与我的组合框不同。
    • 好吧,希望第一段能解决你的问题!
    • 没有什么能解决我的问题!我不明白!我尝试了一个简单的comboxox,但这是同样的问题!
    • 好的,我更新了答案以更清楚我的意思。这有帮助吗?
    • 我认为这是我加载窗口的方式。我尝试了相同的代码,但我尝试使用 usercontrol 的窗口,它的工作!你知道我为什么会有这种行为吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-19
    • 1970-01-01
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    相关资源
    最近更新 更多