1
我在主窗口中有一個集合,我想在用戶控件的網格中顯示它, 什麼是正確的MVVM方式來做到這一點?Binding Observable集合
我在MainWindow中完成了一個observableCollection並將其綁定到了usercontrol中的observableCollection。並在用戶控件中將網格綁定到 集合。
它不工作:(
/// <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;
}
}
主窗口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>
用戶控件:
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;
}
}
用戶控件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>
您可能想發佈一個小例子的代碼。有很多原因可能不起作用。確保你正確設置了DataContext。確保你的ItemsSource綁定正確,等等。 – Robaticus 2010-09-10 12:26:04
你看過這個問題嗎? http://stackoverflow.com/questions/712398/silverlight-binding-with-observablecollections – 2010-09-10 12:35:47
一個紅旗 - 你在主窗口中有一個集合? 「MVVM」這樣做的方法是在ViewModel中創建集合。 – 2010-09-10 13:21:41