绑定wpf UserControl的代码隐藏属性

时间:2013-10-10 09:33:22

标签: wpf user-controls

我正在尝试使用可变数量的按钮创建一个Wpf UserControl 在public string[] MenuItems { get; set; }后面的代码中包含按钮的Text(内容),因此数组中的每个项目都应对应一个按钮。

我试过了:

<UserControl x:Class="MyApp.Controls.MenuButtons"
             xmlns:m="clr-namespace:MyApp.Controls"
             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"
             DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <DockPanel LastChildFill="False"
               Background="{StaticResource ControlBackground}"
               DockPanel.Dock="Top"
               Height="35"
               Margin="5,0,0,0">
        <ItemsControl ItemsSource="{Binding MenuItems}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Button Content="{Binding}"
                            Style="{StaticResource MenuButton}" />
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </DockPanel>
</UserControl>

在如下窗口中使用控件:

<c:MenuButtons MenuItems="..."></c:MenuButtons>

给出错误: 成员“MenuItems”无法识别或无法访问 MenuItems有时在xaml intellisense中被识别,有时不被识别。 窗口有自己作为datacontext:

DataContext="{Binding RelativeSource={RelativeSource Self}}"

1 个答案:

答案 0 :(得分:1)

您的MenuItems属性应为DependancyProperty,以便将其用作绑定目标。

类型应该是string []而不是字符串。

static readonly DependencyProperty MenuItemsProperty = DependencyProperty.Register("MenuItems", typeof(string[]), typeof(MenuButtons), new PropertyMetadata(null));
相关问题