I have a collection in the main window and I want to show it on a grid in a user Control, What is the right MVVM way to do that ?
I've done an observableCollection in the MainWindow And bounded it to an observableCollection in the usercontrol. and in the user control the grid is bounded to the collection.
it doesn't work :(
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public ObservableCollection<string> MyNames
{
get { return (ObservableCollection<string>)GetValue(MyNamesProperty); }
set { SetValue(MyNamesProperty, value); }
}
// Using a DependencyProperty as the backing store for Names. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MyNamesProperty =
DependencyProperty.Register("MyNames", typeof(ObservableCollection<string>), typeof(MainWindow), new UIPropertyMetadata(null));
public MainWindow()
{
MyNames = new ObservableCollection<string>() { "Jonh", "Mary" };
this.InitializeComponent();
DataContext = this;
}
}
MainWindow XAML :
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication3"
x:Class="WpfApplication3.MainWindow"
x:Name="Window"
Title="MainWindow"
UseLayoutRounding="True"
Width="640" Height="480">
<Grid>
<local:NamesControl Names="{Binding MyNames}"></local:NamesControl>
</Grid>
UserControl:
public partial class NamesControl : UserControl
{
public ObservableCollection<string> Names
{
get { return (ObservableCollection<string>)GetValue(NamesProperty); }
set { SetValue(NamesProperty, value); }
}
// Using a DependencyProperty as the backing store for Names. This enables animation, styling, binding, etc...
public static readonly DependencyProperty NamesProperty =
DependencyProperty.Register("Names", typeof(ObservableCollection<string>), typeof(NamesControl), new UIPropertyMetadata(null));
public NamesControl()
{
InitializeComponent();
DataContext = this;
}
}
UserControl XAML:
<UserControl x:Class="WpfApplication3.NamesControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<ItemsControl ItemsSource="{Binding Names}"/>
</Grid>