首页 > 解决方案 > 从单独的 XAML 控制文件中绑定 ComboBox 中的 SelectedItem

问题描述

我在应用程序功能区菜单中有一个组合框,其中所选项目绑定到应用程序 UI 的主题,如下所示:

MainWindow.xaml 中的主题绑定

Theme="{Binding SelectedItem.Tag, ElementName=_themeCombo}"

和组合框

<ComboBox x:Name="_themeCombo" SelectedIndex="0" Width="200">
    <ComboBoxItem Content="Generic" />
    <ComboBoxItem Content="Aero">
        <ComboBoxItem.Tag>
            <xcad:AeroTheme />
        </ComboBoxItem.Tag>
    </ComboBoxItem>
</ComboBox>

主题选择运行良好,但是,由于 MainWindow.xaml 变得很长,我已将菜单功能区(以及组合框)移动到名为“Ribbon.xaml”的单独 UserControl 文件中,并按如下方式引用它:

<local:Ribbon x:Name="RibbonWin" Grid.Row="0" />

然而,这破坏了我的主题选择的绑定链接。Ribbon.xaml 与 mainwindow.xaml 位于同一命名空间中。

如何为名为“_themeCombo”的功能区组合框提供相对路径?

我尝试将 ComboBox 的完整地址放在(功能区的 inc 类名)中,如下所示,但这不起作用:

Theme="{Binding SelectedItem.Tag, ElementName=DrainageDesign.View.Ribbon._themeCombo}"

标签: wpfxamlbindingselecteditemelementname

解决方案


您可以向您添加一个依赖属性Ribbon UserControl并使用它来传输值。请注意,您可以使用比object实际主题更具体的类型

public object SelectedTheme
{
    get { return (object)GetValue(SelectedThemeProperty); }
    set { SetValue(SelectedThemeProperty, value); }
}

public static readonly DependencyProperty SelectedThemeProperty =
    DependencyProperty.Register("SelectedTheme", typeof(object), typeof(Ribbon), new FrameworkPropertyMetadata());

然后将选中的主题绑定到属性

<local:Ribbon x:Name="RibbonWin"
              SelectedTheme="{Binding SelectedItem.Tag, ElementName=_themeCombo}"
              Grid.Row="0" />

并使用功能区内的转移值。我假设你给你的 Ribbon UserControl 一个内部名称_self用于这个例子。您实际上可以使用您选择的任何技术来访问您控件中的属性。

Theme="{Binding SelectedTheme, ElementName=_self}"

推荐阅读