DependencyProperty does not trigger LayoutProcess

本文关键字:LayoutProcess trigger not does DependencyProperty | 更新日期: 2023-09-27 18:29:14

我正在编写自己的Panel(WPF)来绘制模型。我有一个Model DependencyProperty,我希望对我的Model的任何更改都会影响LayoutProcess。

ModelProperty = DependencyProperty.Register("Model", typeof(Model), typeof(ModelPanel),
            new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsMeasure));

我应该如何实现我的模型类,以便任何更改都会影响LayoutProcess?我已尝试INotifyPropertyChanged。但它没有起作用。

DependencyProperty does not trigger LayoutProcess

很抱歉,但我认为你可能做得不对。

在WPF中,面板只是用来定义事物的布局方式。

  • StackPanel可以水平或垂直放置一个接一个的东西
  • WrapPanel将事物放置在一行/列中,然后包装到下一行
  • 画布可以将事物定位在x、y点

由于您正在尝试使用面板,我假设您的模型中有一组东西。我们可以使用ListBox处理集合,我们可以为其提供正确的面板类型。即

<ListBox ItemsSource="{Binding MyThings}">
    <ListBox.ItemsPanel>
        <StackPanel Orientation="Vertical"/>
    </ListBox.ItemsPanel>
</ListBox>

然而,这通常只是给我们一个类名列表,每个类名代表您的一个Things,您需要告诉WPF如何显示它,为此您使用DataTemplate。您可以在许多地方,在资源部分(用于控件、窗口或应用程序)或您需要的地方定义这些

<ListBox ItemsSource="{Binding MyThings}">
    <ListBox.ItemsPanel>
        <StackPanel Orientation="Vertical"/>
    </ListBox.ItemsPanel>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}"/> <!-- Assuming each thing has a name property-->
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

更新:或者,如果您有不同类型的项目显示

<ListBox ItemsSource="{Binding MyThings}">
    <ListBox.ItemsPanel>
        <Canvas/>
    </ListBox.ItemsPanel>
    <ListBox.Resources>
        <DataTemplate TargetType="{x:Type MyLine}">
            <Line x1="{Binding Left}" x2="{Binding Right}" 
                  y1="{Binding Top}" y2="{Binding Bottom}"/>
        </DataTemplate>
        <DataTemplate TargetType="{x:Type MyRectangle}">
            <Border Canvas.Left="{Binding Left}" Canvas.Right="{Binding Right}" 
                    Canvas.Top="{Binding Top}" Canvas.Bottom="{Binding Bottom}"/>
        </DataTemplate>        
    </ListBox.Resources>
</ListBox>

还请阅读Josh Smith关于MVVM的文章,其中有很多例子和良好的实践,并将介绍一种保持模型整洁的模式。