C# 将元素绑定到子对象XAML

C# 将元素绑定到子对象XAML,c#,.net,wpf,xaml,windows-store-apps,C#,.net,Wpf,Xaml,Windows Store Apps,首先是守则: MyStyle.xaml <Style x:Key="MyStyle" TargetType="Button"> <Setter Property="ContentTemplate"> <Setter.Value> <DataTemplate> <Grid> <TextBlock x:Name="M

首先是守则:

MyStyle.xaml

<Style x:Key="MyStyle" TargetType="Button">
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <Grid>
                    <TextBlock x:Name="MyTextGen" Text="{TemplateBinding Content}"/>
                </Grid>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>
MyUserControl.xaml

<UserControl>
    <Grid>
        <ItemsControl ItemsSource="{Binding Path=Buttons}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Button Style="{StaticResource MyStyle}" Content="{Binding}" Tag="{Binding}" />
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Grid>
</UserControl>
MyPage.xaml

Info.cs

我想通过主页在MyTextGen中绑定MyDict的第一个和第二个,可以吗?

MyStyle.xaml

<Style x:Key="MyStyle" TargetType="Button">
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <Grid>
                    <TextBlock x:Name="MyTextGen" Text="{TemplateBinding Content}"/>
                </Grid>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>
MyUserControl.xaml

<UserControl>
    <Grid>
        <ItemsControl ItemsSource="{Binding Path=Buttons}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Button Style="{StaticResource MyStyle}" Content="{Binding}" Tag="{Binding}" />
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Grid>
</UserControl>
MyUserControl.xaml.cs

public IEnumerable<string> Buttons {
    get { return (IEnumerable<string>)GetValue(ButtonsProperty); }
    set { SetValue(ButtonsProperty, value); }
}

public static readonly DependencyProperty ButtonsProperty =
    DependencyProperty.Register("Buttons", typeof(IEnumerable<string>),
    typeof(MyUserControl));
MainWindow.xaml

<Border>
    <cat:MyUserControl Buttons="{Binding Buttons}" />
</Border>
MainWindow.xaml.cs

public IEnumerable<string> Buttons { get; set; }
private Dictionary<string, string> MyDict = new Dictionary<string, string> { { "First", "MyFirst" }, { "Second", "MySecond" } };

public MainWindow() {
    this.DataContext = this;
    Buttons = MyDict.Keys;
    InitializeComponent();
}

好的,我不能打招呼-uu-很抱歉。
<Border>
    <cat:MyUserControl Buttons="{Binding Buttons}" />
</Border>
public IEnumerable<string> Buttons { get; set; }
private Dictionary<string, string> MyDict = new Dictionary<string, string> { { "First", "MyFirst" }, { "Second", "MySecond" } };

public MainWindow() {
    this.DataContext = this;
    Buttons = MyDict.Keys;
    InitializeComponent();
}