Binding ItemsSource bên trong một UserControl WPF

Trong WPF để binding ItemsSource bên trong một UserControl các bạn làm như sau:

Đầu tiên các bạn cần phải thêm một property  vào UserControl của mình.  ví dụ ở đây chúng ta thêm ItemsSource vào trong file code .cs

public partial class GridUserControl : UserControl
{
    public object ItemsSource
    {
        get { return (object)GetValue(ItemsSourceProperty); }
        set { SetValue(ItemsSourceProperty, value); }
    }

    public static readonly DependencyProperty ItemsSourceProperty =
        DependencyProperty.Register("ItemsSource", typeof(object), typeof(GridUserControl), new PropertyMetadata(null));

      public GridUserControl ()
        {
            InitializeComponent();
        }

}

và trong file XAML các bạn định nghĩa như sau

<UserControl x:Class="MyApp.GridUserControl"
             xmlns:local="clr-namespace:MyApp">
    <dxg:GridControl ItemsSource="{Binding ItemsSource, RelativeSource={RelativeSource AncestorType=local:GridUserControl}}" />

</UserControl>

Và sau đó ở View nào sử dụng UserControl bạn chỉ việc binding đối tượng vào

<Window x:Class="MyApp.Window1"
        xmlns:local="clr-namespace:MyApp">
    <Grid>
        <local:GridUserControl ItemsSource="{Binding Items1}"></local:GridUserControl>
        <local:GridUserControl ItemsSource="{Binding Items2}"></local:GridUserControl>
    </Grid>
</Window>

 

Nguồn https://stackoverflow.com/questions/35399129/binding-to-datagrids-itemsource-in-usercontrol

Leave a Reply

Your email address will not be published.