0

So I have a UserControl that contains a ListView and a Button. I have included my UserControl in Window1.xaml, but I don't know what do I have to do so I can access my ListView control in Window1.xaml.cs .

What else should I need to do ? What is the best aproach here ?

Adrian
  • 18,026
  • 34
  • 104
  • 199

1 Answers1

3

That is not something you should be doing, instead create properties on the UserControl which the internals are bound to, then you have a clean interface.

e.g.

<UserControl Name="control" ...>
    <ListView ItemsSource="{Binding ItemsSource, ElementName=control}">
        <!-- ... -->
public class MyUserControl : UserControl
{
    public static readonly DependencyProperty ItemsSourceProperty =
        DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(MyUserControl), new UIPropertyMetadata(null));
    public IEnumerable ItemsSource
    {
        get { return (IEnumerable)GetValue(ItemsSourceProperty); }
        set { SetValue(ItemsSourceProperty, value); }
    }
}
<Window ...>
    <local:MyUserControl x:Name="myUc"/>
        <!-- ... -->
myUc.ItemsSource = new string[] { "Lorem", "Ipsum" };
H.B.
  • 142,212
  • 27
  • 297
  • 366