我面临的一个问题与工作,而WPF组合框 。 我的情况是,我有一个显示某些值的组合框。 我加入ContentControl
s到组合框” Items
属性。 我已绑定的Content
,这些ContentControl中的一些数据源,这样我可以动态改变的内容。 问题是,如果所选择项的内容改变组合框的项目下拉更新,但在组合框SelectionChange项保持不变。
有什么建议吗?
我面临的一个问题与工作,而WPF组合框 。 我的情况是,我有一个显示某些值的组合框。 我加入ContentControl
s到组合框” Items
属性。 我已绑定的Content
,这些ContentControl中的一些数据源,这样我可以动态改变的内容。 问题是,如果所选择项的内容改变组合框的项目下拉更新,但在组合框SelectionChange项保持不变。
有什么建议吗?
除了直接组合框里面添加ContentControl中的,使用一个DataTemplate(ItemsTemplate)或ItemContainerStyle。 由于自动生成ComboBoxItem不知道你的点击,因为ContentControl中吃了鼠标按下并隐藏ComboboxItem。 组合框项目负责设置IsSelectedProperty并触发的SelectionChanged发生。
我已经解决了用不同的方式这个问题。
组合框的SelectedItem是不是它显示却是你选择什么。 当你选择一个项目的组合框采用组合框显示在SelectionBox的模板没有的SelectedItem,S模板。 如果你将进入组合框的VisualTree,你会看到它有一个包含一个TextBlock一个ContentPresenter这TextBlock的分配与所选项目的文本。
所以,我做什么,在SelectionChanged事件处理程序我看了使用VisualTreeHelper该ContentPresenter内的TextBlock,然后我绑定这个TextBlock的Text属性设置为我的ContentControl中(的SelectedItem)的内容属性。
在组合框的的SelectionChanged evetn处理我写的:
ModifyCombox(cmbAnimationBlocks, myComboBox.SelectedItem.As<ContentControl>());
这方法是:
private static void ModifyCombox(DependencyObject comboBox, ContentControl obj)
{
if (VisualTreeHelper.GetChildrenCount(comboBox) > 0)
{
WalkThroughElement(comboBox, obj);
}
}
private static void WalkThroughElement(DependencyObject element, ContentControl contentControl)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
{
if (element.GetType() == typeof(ContentPresenter))
{
ContentPresenter contentPresenter = element.As<ContentPresenter>();
TextBlock textBlock = VisualTreeHelper.GetChild(contentPresenter, 0).As<TextBlock>();
textBlock.SetBinding(TextBlock.TextProperty, new Binding("Content")
{
Source = contentControl
});
contentPresenter.Content = textBlock;
}
else
{
DependencyObject child = VisualTreeHelper.GetChild(element, i).As<FrameworkElement>();
WalkThroughElement(child, contentControl);
}
}
if (VisualTreeHelper.GetChildrenCount(element) == 0 && element.GetType() == typeof(ContentPresenter))
{
ContentPresenter contentPresenter = element.As<ContentPresenter>();
TextBlock textBlock = new TextBlock();
textBlock.SetBinding(TextBlock.TextProperty, new Binding("Content")
{
Source = contentControl
});
contentPresenter.Content = textBlock;
}
}