我有点惊讶,无法通过 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。