1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

WPF独自コントロール ItemsSourceのバインドについて~備忘録

Posted at

はじめに

WPFの独自コントロール作成の際にリスト(コレクション)をBindingするための方法につまずいていたが、解決方法が見つかったので備忘録として記録する。

この記事でわかる・できること

  • WPFで独自コントロールを作成しデータをBindingする方法

動作環境・使用するツールや言語

  • C# WPF
  • net8.0

コード一覧

独自コントロール側
ListBoxを配置し、ItemsSourceをBindingしています。

CustomControl.xaml
<UserControl x:~~~~~
             xmlns:~~~~~
             x:Name="root">
             <ListBox
                 DataContext="{Binding ElementName=root}"
                 ItemsSource="{Binding ItemsSource}"/>
</UserControl>

DependencyPropertyを使用します。
IEnumerableを使用します。

CustomControl.xaml.cs
public partial class CustomControl:UserControl
{
    public IEnumerable ItemsSource
    {
        get { return (IEnumerable)GetValue(ItemsSourceProperty); }
        set { SetValue(ItemsSourceProperty, value); }
    }
    public static readonly DependencyProperty ItemsSourceProperty = 
        DependencyProperty.Register("ItemsSource",typeof(IEnumerable),
            typeof(AutoSuggestBox),new PropertyMetadata(null));
}

使用する側
CustomControlを配置しItemsSourceにItemsをBindingしています。

MainWindow.xaml
<Window xmlns;local="~~~~~~">
    <Window.DataContext>
        <local:MainWindow_ViewModel/>
    </Window.DataContext>
    
    <local:CustomContorl ItemsSource="{Binding Items}"/>
</Window>

今回、ViewModelのコンストラクタでリストの中身を宣言しています。

MainWindouw_ViewModel.cs
public class MainWindow_ViewModel
{
    public List<string> Items { get; set; }
    public MainWindow_ViewModel()
    {
        Items = new List<string>(){"AAA","BBB","CCC"};
    }
}

これで外部からのデータをBindingできるようになります。

参考資料

UserControl のカスタム ItemsSource プロパティ

おわりに・まとめ

独自コントロールを使用する場合ですので使用する頻度は少ないと思いますが備忘録ですのでご容赦ください。
また、今回のリスト(コレクション)を使用した部分一致検索の方法を別記事で記載できれbと思います。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?