5

ボタンの ObservableCollection があります。

public partial class MainWindow : Window   
     {
        public ObservableCollection<Button> myBtCollection { get; set; }

        public MainWindow()
        {
            InitializeComponent();

            myBtCollection = new ObservableCollection<Button>();

            Button bot1 = new Button { Width = 200, Height = 25, Content = "Boton 1" };
            Button bot2 = new Button { Width = 150, Height = 50, Content = "Boton 2" };
            Button bot3 = new Button { Width = 100, Height = 100, Content = "Boton 3" };

            myBtCollection.Add(bot1);
            myBtCollection.Add(bot2);
            myBtCollection.Add(bot3);
            myBtCollection.Add(bot1);
            myBtCollection.Add(bot3);
            myBtCollection.Add(bot2);
            myBtCollection.Add(bot1);
        }
    }

そのコレクションを StackPanel にバインドしたいと考えています (この例では定数コレクションですが、最終的には変数になります)。これは私のXAMLです:

<Window x:Name="mainWindow" x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">

    <Grid>
        <StackPanel x:Name="stack">

        </StackPanel>

        <ItemsControl  Width="Auto" 
                       Height="Auto"
                       ItemsSource="{Binding ElementName=mainWindow, Path=myBtCollection}">      
        </ItemsControl>


    </Grid>
</Window>

ItemsControl を使用して実現できると読みましたが、それを終了する方法がわかりません。(分離コードで DataContext を設定する必要がありますか?)

4

2 に答える 2

5

@inxs からのコメントに同意します。InitializeComponent()しかし、myBtCollection の作成後にこの作品を動かすには

public MainWindow()
{
    myBtCollection = new ObservableCollection<Button>();
    ...

    InitializeComponent();
}

またはINotifyPropertyChangedを実装しmyBtCollectionます。

于 2013-05-27T12:31:05.677 に答える
4
  1. ItemsControl は既に Vertical StackPanel を使用しています。
  2. 視覚的なレイアウトに使用される StackPanel にデータをバインドすることはできません。

別のパネルを使用したり、StackPanels の向きを変更したい場合は、ItemsControl のプロパティ「ItemsPanel」を使用して、次のように設定できます。

<ItemsControl.Style>
            <Style TargetType="{x:Type ItemsControl}">
                <Setter Property="ItemsPanel">
                    <Setter.Value>
                        <ItemsPanelTemplate>
                            <StackPanel Orientation="Horizontal"/>
                        </ItemsPanelTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
 </ItemsControl.Style>
于 2013-05-27T12:24:58.813 に答える