WPF如何在UserControl上公开字段

时间:2010-11-11 20:05:27

标签: wpf user-controls

我有一个简单的应用程序,只有一个窗口和一个用户控件。用户控件有一个列表框。用户控件位于Window上,我想将用户控件的列表框绑定到窗口数据上下文中的元素。

我能够找到的示例在用户控件上具有CLR属性,这些属性是通过代码而不是通过XAML访问的。

<Window x:Class="WpfApplication2b.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:WpfApplication2b="clr-namespace:WpfApplication2b" Title="MainWindow" Height="410" Width="520">
<Grid>
    <WpfApplication2b:MyUserControl></WpfApplication2b:MyUserControl>
</Grid>

这是用户控件本身。

<UserControl x:Class="WpfApplication2b.MyUserControl"
         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="300" d:DesignWidth="300">
<Grid Background="#FFD8AA13">
    <ListBox Height="276" HorizontalAlignment="Left" Margin="12,12,0,0" Name="listBox1" VerticalAlignment="Top" Width="276" />
</Grid>

正如您所看到的,它只是一个不同颜色背景的列表框。我不知道下一步该去哪了:)

我猜我需要在列表框的属性后面添加一个代码作为依赖属性?

编辑:我添加了一个dependencyProperty,但我认为我不是那么重要。

    public partial class MyUserControl : UserControl
{
    public static readonly DependencyProperty ListBoxProperty;

    static MyUserControl()
    {
        FrameworkPropertyMetadata md = new FrameworkPropertyMetadata();
        MyUserControl.ListBoxProperty = DependencyProperty.Register("MyListBox", typeof (ListBox),
                                                                    typeof (MyUserControl), md);

    }

    public ListBox MyListBox
    {
        get
        {
            return (ListBox) GetValue(ListBoxProperty);
        }
        set
        {
            SetValue(ListBoxProperty, value);
        }
    }

    public MyUserControl()
    {
        InitializeComponent();
    }
}

2 个答案:

答案 0 :(得分:1)

您的UserControl将从Window继承DataContext,因此您可以绑定ListBox上的属性,就好像它是在Window中声明的那样。为了使控件更加灵活,您可以为要使用的DataContext(即ItemsSource集合)中的数据项声明依赖项属性,并将它们传递到控件中,而不是传递ListBox

答案 1 :(得分:0)

我认为这个问题/答案几乎就是你要找的。本质上,您将需要创建依赖项属性(使用AddOwner注册方法)并在ListBox的{​​{1}}上设置DataBinding以挂钩依赖项属性。答案中的示例对ItemsSource执行相同的操作,对于ComboBox应该几乎相同。

Exposing inner Control properties for binding in WPF

相关问题