将元素绑定到子对象XAML

时间:2015-03-23 14:54:04

标签: 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="MyTextGen" Text="Foo"/>
                </Grid>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

MyUserControl.xaml

<UserControl x:Name="Mycontrol">
    <Grid>
        <Button x:Name="Btn1" Style="{StaticResource MyStyle}"/>
        <Button x:Name="Btn2" Style="{StaticResource MyStyle}"/>
    </Grid>
</UserControl>

MyPage.xaml

<common:MainPage x:Name="MainPage">
    <Grid>
        <Popup x:Name="CatTool" IsOpen="False" HorizontalAlignment="Center" VerticalAlignment="Center" 
               Margin="0 0 300 500">
            <cat:MyControl >
                <cat:MyContro.Transitions>
                    <TransitionCollection>
                        <PopupThemeTransition/>
                    </TransitionCollection>
                </cat:MyContro.Transitions>
            </cat:CatPagecontrol>
        </Popup>
    </Grid>
</common:MainPage>

Info.cs

MyDict = new Dictionary<string, string>
{
    {"First", "MyFirst"},
    {"Second", "MySecond")}
};

我想通过MainPage绑定MyTextGen中的MyDict“First”和“Second”,是否可能?

1 个答案:

答案 0 :(得分:0)

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();
}