「Androidは電気羊の夢を見るか」を読みたい管理者のブログ

仕事などでの色々な発見を記事にしてます。不定期更新。

ボタンの動的配置で嵌った

ボタンを横並びに動的に追加したい - 「Androidは電気羊の夢を見るか」を読みたい管理者のブログ
で、ボタンの動的追加には対応できたのだが、
はて困った、動的に追加したボタンにCommandを定義しようと思ったら

<ListBox>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Button
                Width="100"
                Command="{Binding Path=HelloCommand}"
                CommandParameter="{Binding RelativeSource={RelativeSource Self},Path=Content}"
                Content="{Binding Tell}">
            </Button>
        </DataTemplate>
    </ListBox.ItemTemplate>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>

てやると思います。普通に考えて。
でも上手くいかない。色々試してる中で
これ、ItemsSourceに定義したコマンド呼んでるじゃん
って事に気づきましたとさ。

で、色々調べてて

<ListBox x:name=parent>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Button
                Width="100"
                Command="{Binding Path=DataContext.HelloCommand,ElementName=parent}"
                CommandParameter="{Binding RelativeSource={RelativeSource Self},Path=Content}"
                Content="{Binding Tell}">
            </Button>
        </DataTemplate>
    </ListBox.ItemTemplate>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>

とすればうまく動きましたとさ。

ポイントは、ListBoxに名前をつけてBinding Pathの指定の仕方を

Command="{Binding Path=DataContext.HelloCommand,ElementName=parent}"

てやる。
参考:
WPF MVVM Command Binding inside a DataTemplate | renanleandrof