【发布时间】:2010-10-27 18:01:55
【问题描述】:
我有点惊讶,无法通过 XAML 为 Canvas.Children 设置绑定。我不得不求助于看起来像这样的代码隐藏方法:
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
DesignerViewModel dvm = this.DataContext as DesignerViewModel;
dvm.Document.Items.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Items_CollectionChanged);
foreach (UIElement element in dvm.Document.Items)
designerCanvas.Children.Add(element);
}
private void Items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
ObservableCollection<UIElement> collection = sender as ObservableCollection<UIElement>;
foreach (UIElement element in collection)
if (!designerCanvas.Children.Contains(element))
designerCanvas.Children.Add(element);
List<UIElement> removeList = new List<UIElement>();
foreach (UIElement element in designerCanvas.Children)
if (!collection.Contains(element))
removeList.Add(element);
foreach (UIElement element in removeList)
designerCanvas.Children.Remove(element);
}
我宁愿像这样在 XAML 中设置一个绑定:
<Canvas x:Name="designerCanvas"
Children="{Binding Document.Items}"
Width="{Binding Document.Width}"
Height="{Binding Document.Height}">
</Canvas>
有没有办法在不采用代码隐藏方法的情况下完成此任务?我已经对这个主题进行了一些谷歌搜索,但没有针对这个特定问题提出太多建议。
我不喜欢我目前的方法,因为它让 View 意识到它是 ViewModel,从而破坏了我漂亮的 Model-View-ViewModel。
【问题讨论】:
标签: c# wpf data-binding .net-3.5 canvas