在WPF中公开绑定的内部Control属性

fbl*_*fbl 40 wpf binding user-controls combobox

[编辑]:我想出了如何自己做这件事.我发布了我的解决方案,希望能在几天谷歌上搜索其他人.如果您是WPF大师,请查看我的解决方案,让我知道是否有更好/更优雅/更有效的方法来做到这一点.特别是,我有兴趣知道我不知道的...这个解决方案怎么会让我不知所措?问题实际上归结为暴露内部控制属性.

问题:我正在创建一些代码,以便在WPF中为XML文件自动生成数据绑定GUI.我有一个xsd文件,可以帮助我确定节点类型等.简单的键/值元素很容易.

当我解析这个元素时:

<Key>value</Key>
Run Code Online (Sandbox Code Playgroud)

我可以创建一个新的'KeyValueControl'并设置DataContext为这个元素.KeyValue被定义为UserControl,并且只有一些简单的绑定.它适用于任何简单的XElement.

此控件中的XAML如下所示:

<Label Content={Binding Path=Name} /> 
<TextBox Text={Binding Path=Value} />
Run Code Online (Sandbox Code Playgroud)

结果是一行包含带有元素名称的标签和一个带有我可以编辑的值的文本框.

现在,有时我需要显示查找值而不是实际值.我想创建一个类似于上面KeyValueControl的'KeyValueComboBox',但是能够指定(基于文件中的信息)ItemsSource,Display和Value路径.'Name'和'Value'绑定与KeyValueControl相同.

我不知道标准用户控件是否可以处理这个问题,或者我是否需要从Selector继承.

控件中的XAML看起来像这样:

<Label Content={Binding Path=Name} /> 
<ComboBox SelectedValue={Binding Path=Value}
          ItemsSource={Binding [BOUND TO THE ItemsSource PROPERTY OF THIS CUSTOM CONTROL]
          DisplayMemberPath={Binding [BOUND TO THE DisplayMemberPath OF THIS CUSTOM CONTROL]
          SelectedValuePath={Binding [BOUND TO THE SelectedValuePath OF THIS CUSTOM CONTROL]/>
Run Code Online (Sandbox Code Playgroud)

在我的代码中,我会做这样的事情(假设这个节点是'Thing'并且需要显示Things列表,以便用户可以选择ID:

var myBoundComboBox = new KeyValueComboBox();
myBoundComboBox.ItemsSource = getThingsList();
myBoundComboBox.DisplayMemberPath = "ThingName";
myBoundComboBox.ValueMemberPath = "ThingID"
myBoundComboBox.DataContext = thisXElement;
...
myStackPanel.Children.Add(myBoundComboBox)
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:

1)我应该从Control或Selector继承我的KeyValueComboBox吗?

2)如果我应该从Control继承,我如何公开内部组合框的ItemsSource,DisplayMemberPath和ValueMemberPath以进行绑定?

3)如果我需要继承Selector,有人可以提供一个小例子来说明我如何开始使用它吗?再说一次,我是WPF的新手,所以如果这是我需要走的路,一个好的,简单的例子真的会有所帮助.

fbl*_*fbl 48

我最终想出了如何自己做这件事.我在这里发布答案,以便其他人可以看到一个有效的解决方案,也许WPF大师会来,并告诉我一个更好/更优雅的方式来做到这一点.

所以,答案最终成为#2.揭示内在属性是正确的答案.设置它实际上非常简单..一旦你知道如何做到这一点.没有很多完整的例子(我可以找到),所以希望这个可以帮助遇到这个问题的其他人.

ComboBoxWithLabel.xaml.cs

这个文件中最重要的是使用DependencyProperties.请注意,我们现在正在做的只是公开属性(LabelContent和ItemsSource).XAML将负责将内部控件的属性连接到这些外部属性.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections;

namespace BoundComboBoxExample
{
    /// <summary>
    /// Interaction logic for ComboBoxWithLabel.xaml
    /// </summary>
    public partial class ComboBoxWithLabel : UserControl
    {
        // Declare ItemsSource and Register as an Owner of ComboBox.ItemsSource
        // the ComboBoxWithLabel.xaml will bind the ComboBox.ItemsSource to this
        // property
        public IEnumerable ItemsSource
        {
            get { return (IEnumerable)GetValue(ItemsSourceProperty); }
            set { SetValue(ItemsSourceProperty, value); }
        }

        public static readonly DependencyProperty ItemsSourceProperty =
          ComboBox.ItemsSourceProperty.AddOwner(typeof(ComboBoxWithLabel));

        // Declare a new LabelContent property that can be bound as well
        // The ComboBoxWithLable.xaml will bind the Label's content to this
        public string LabelContent
        {
            get { return (string)GetValue(LabelContentProperty); }
            set { SetValue(LabelContentProperty, value); }
        }

        public static readonly DependencyProperty LabelContentProperty =
          DependencyProperty.Register("LabelContent", typeof(string), typeof(ComboBoxWithLabel));

        public ComboBoxWithLabel()
        {
            InitializeComponent();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

ComboBoxWithLabel.xaml

Xaml非常简单,除了Label和ComboBox ItemsSource上的绑定.我发现获得这些绑定的最简单方法是在.cs文件中声明属性(如上所述),然后使用VS2010设计器从属性窗格设置绑定源.从本质上讲,这是我所知道的将内部控件的属性绑定到基本控件的唯一方法.如果有更好的方法,请告诉我.

<UserControl x:Class="BoundComboBoxExample.ComboBoxWithLabel"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="28" d:DesignWidth="453" xmlns:my="clr-namespace:BoundComboBoxExample">
    <Grid>
        <DockPanel LastChildFill="True">
            <!-- This will bind the Content property on the label to the 'LabelContent' 
                 property on this control-->
            <Label Content="{Binding Path=LabelContent, 
                             RelativeSource={RelativeSource FindAncestor, 
                                             AncestorType=my:ComboBoxWithLabel, 
                                             AncestorLevel=1}}" 
                   Width="100" 
                   HorizontalAlignment="Left"/>
            <!-- This will bind the ItemsSource of the ComboBox to this 
                 control's ItemsSource property -->
            <ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, 
                                    AncestorType=my:ComboBoxWithLabel, 
                                    AncestorLevel=1}, 
                                    Path=ItemsSource}"></ComboBox>
            <!-- you can do the same thing with SelectedValuePath, 
                 DisplayMemberPath, etc, but this illustrates the technique -->
        </DockPanel>

    </Grid>
</UserControl>
Run Code Online (Sandbox Code Playgroud)

MainWindow.xaml

使用它的XAML根本不是很有趣......这正是我想要的.您可以通过所有标准WPF技术设置ItemsSource和LabelContent.

<Window x:Class="BoundComboBoxExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="86" Width="464" xmlns:my="clr-namespace:BoundComboBoxExample"
        Loaded="Window_Loaded">
    <Window.Resources>
        <ObjectDataProvider x:Key="LookupValues" />
    </Window.Resources>
    <Grid>
        <my:ComboBoxWithLabel LabelContent="Foo"
                              ItemsSource="{Binding Source={StaticResource LookupValues}}"
                              HorizontalAlignment="Left" 
                              Margin="12,12,0,0" 
                              x:Name="comboBoxWithLabel1" 
                              VerticalAlignment="Top" 
                              Height="23" 
                              Width="418" />
    </Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)

对于完整性清酒,这是MainWindow.xaml.cs

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        ((ObjectDataProvider)FindResource("LookupValues")).ObjectInstance =
            (from i in Enumerable.Range(0, 5)
             select string.Format("Bar {0}", i)).ToArray();

    }
}
Run Code Online (Sandbox Code Playgroud)