0

開いているウィンドウのリスト (より具体的には、ウィンドウの名前またはタイトル) を表示するプログラムの一部を作成しようとしています。

したがって、ビューの XAML は次のようになります。

<Window.DataContext>
  <local:ViewModel />
</Window.DataContext>
<ItemsControl ItemsSource="{Binding Windows}" />

クラスは次のようになりViewModelます。

public ObservableCollection<Window> Windows { get; set; }

public ViewModel()
{
  this.Windows = new ObservableCollection<Window>();
  this.Windows.Add(new Window());
}

これにより、プログラム (およびデザイナー ビュー) がスローされます。InvalidOperationException: Window must be the root of the tree. Cannot add Window as a child of Visual.

問題は、実際にそれ自体をクラスとしてではなくコントロールとしてItemsControl追加したいと考えていることのようです(ウィンドウにテキストまたは同様のものを表示することが期待されます)。WindowSystem.Windows.Window

を追加してみまし<ItemsControl.ItemTemplate><DataTemplate>...たが、これは同じ結果になるようです。

WindowHolder最後に、 a の単一のパブリック プロパティを持つダミー クラスを作成してみましたWindow。それは機能しているように見えますが、もっと単純であるべきだと感じていることを行うには、本当に洗練されていないように思えます。

tl;dr

質問は、「ビュー モデルItemsControlの にバインドされた WPF にウィンドウ タイトルのリストを (できれば XAML で) 表示するにはどうすればよいですか?ObservableCollection<Window>

4

4 に答える 4

2

ListBoxの代わりにa を使用できますItemsControl

<ListBox ItemsSource="{Binding Windows}">
    <ListBox.Resources>
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Black" />
        <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Transparent" />
    </ListBox.Resources>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Title}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

問題は、ジェネリックにコントロールを追加するためのデフォルトの動作ItemsControlによりContentPresenter、コントロール自体にラップされることです。したがって、コレクションWindowsをコンテナとして に追加する必要がありますItemsControlItemsPresenter、例外に記載されている理由で失敗します。ListBoxラッピングコンテナはListBoxItemsではなく であるため、機能しWindowsます。で をサポートするには、 ではないコンテナを返す独自のカスタム コントロールを に実装する必要がありWindowます。ItemsControlItemsControlWindow

于 2013-09-05T15:10:20.157 に答える
0

さて、私がすることは次のとおりです。

  • ウィンドウ、つまり Title プロパティを持つ IWindow のインターフェイス ラッパーを (既に述べたように) 作成します。
  • すべての Windows は IWindow を実装します
  • Window の代わりに IWindow の Observable コレクションを作成します。
于 2013-09-05T15:01:50.137 に答える