如何绑定附加属性

本文关键字:属性 绑定 何绑定 | 更新日期: 2023-09-27 18:00:03

我正在尝试自己学习WPF,这有点困难。我需要知道如何通过绑定设置附加属性的值。附加的属性Grid.Row和Grid.RowSpan是绑定的目标,而不是源。StackOverflow上也有人提出过类似的问题,但这些问题都是由真正了解WPF的人提出和回答的,或者涉及到价值转换器等复杂问题。我还没有找到一个对我来说适用和理解的答案。

在这种情况下,我有一个代表全天日程的网格,我想向其中添加事件。每个事件都将从特定的网格行开始,并跨越多行,具体取决于事件的开始时间和持续时间。我的理解是,您必须使用依赖属性作为绑定的源,因此我的事件对象ActivityBlock具有StartIncrementDurationIncrements依赖属性来描述它在网格上的位置。

就是这样,这就是我想要做的:通过绑定在网格中定位UserControl。

我相信我的问题很可能是在我的MainWindow XAML中,在网格上设置了错误的绑定。(请注意,我在构造函数中以编程方式创建网格行,所以不要在下面的XAML中查找它们)。

当我运行应用程序时,事件会被创建,但它不会显示在网格上的正确位置,就好像grid.Row和grid.RowSpan从未被更新一样。绑定Grid.Row和Grid.RowSpan是否不可能?如果没有,我做错了什么?

这里是MainWindow.xaml,我的问题很可能是:

<Window x:Class="DayCalendar.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:DayCalendar"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525" Activated="Window_Activated"
        >
  <DockPanel LastChildFill="True">
    <Rectangle Width="50" DockPanel.Dock="Left"/>
    <Rectangle Width="50" DockPanel.Dock="Right"/>
    <Grid x:Name="TheDay" Background="#EEE">
      <ItemsControl ItemsSource="{Binding Path=Children}">
        <ItemsControl.ItemsPanel>
          <ItemsPanelTemplate>
            <Grid />
          </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemContainerStyle>
          <Style TargetType="ContentPresenter">
            <Setter Property="Grid.Row" Value="{Binding Path=StartIncrement}" />
            <Setter Property="Grid.RowSpan" Value="{Binding Path=DurationIncrements}" />
          </Style>
        </ItemsControl.ItemContainerStyle>
      </ItemsControl>
    </Grid>
  </DockPanel>
</Window>

以下是主窗口的代码隐藏文件:

using System;
using System.Windows;
using System.Windows.Controls;
using DayCalendar.MyControls;
namespace DayCalendar {
  public partial class MainWindow : Window {
    public MainWindow() {
      InitializeComponent();
      var rowDefs = TheDay.RowDefinitions;
      rowDefs.Clear();
      for ( int ix = 0; ix < ( 60 / ActivityBlock.MINUTES_PER_INCREMENT ) * 24; ix += 1 ) {
        rowDefs.Add( new RowDefinition() );
      }
    }
    private void Window_Activated( object sender, EventArgs e ) {
      if ( m_firstActivation ) {
        m_firstActivation = false;
        var firstActivity = new ActivityBlock();
        var today = DateTime.Now.Date;
        var startTime = today.AddHours( 11.5 );
        var durationSpan = new TimeSpan( 1, 0, 0 );
        firstActivity.SetTimeSpan( startTime, durationSpan );
        TheDay.Children.Add( firstActivity );
      }
    }
    private bool m_firstActivation = true;
  }
}

这是ActivityBlock代码:

using System;
using System.Windows;
using System.Windows.Controls;
namespace DayCalendar.MyControls {
  public partial class ActivityBlock : UserControl {
    public int StartIncrement {
      get { return ( int ) GetValue( StartIncrementProperty ); }
      set { SetValue( StartIncrementProperty, value ); }
    }
    public int DurationIncrements {
      get { return ( int ) GetValue( DurationIncrementsProperty ); }
      set { SetValue( DurationIncrementsProperty, value ); }
    }
    public ActivityBlock() {
      InitializeComponent();
    }
    public void SetTimeSpan( DateTime startTime, TimeSpan duration ) {
      int startMinute = startTime.Hour * 60 + startTime.Minute;
      int durationMinutes = ( int ) duration.TotalMinutes;
      StartIncrement = startMinute / MINUTES_PER_INCREMENT;
      DurationIncrements = Math.Max( 1, durationMinutes / MINUTES_PER_INCREMENT );
    }
    static ActivityBlock() {
      var thisType = typeof( ActivityBlock );
      var affectsArrangeAndMeasure = FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure;
      int startIncrementDefault = 0;
      StartIncrementProperty = DependencyProperty.Register(
        nameof( StartIncrement ),
        startIncrementDefault.GetType(),
        thisType,
        new FrameworkPropertyMetadata( startIncrementDefault, affectsArrangeAndMeasure )
      );
      int durationIncrementsDefault = 1;
      DurationIncrementsProperty = DependencyProperty.Register(
        nameof( DurationIncrements ),
        durationIncrementsDefault.GetType(),
        thisType,
        new FrameworkPropertyMetadata( startIncrementDefault, affectsArrangeAndMeasure )
      );
    }
    public const int MINUTES_PER_INCREMENT = 6; // 1/10th of an hour
    static public readonly DependencyProperty StartIncrementProperty;
    static public readonly DependencyProperty DurationIncrementsProperty;
  }
}

相应的XAML并不有趣,但如果需要的话,我会包含它:

<UserControl x:Class="DayCalendar.MyControls.ActivityBlock"
             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" 
             xmlns:local="clr-namespace:DayCalendar.MyControls"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
  <Border BorderThickness="3" BorderBrush="Black" Background="Chartreuse">
    <DockPanel LastChildFill="True">
      <TextBlock TextWrapping="WrapWithOverflow">Event Description</TextBlock>
    </DockPanel>
  </Border>
</UserControl>

如何绑定附加属性

可以绑定Grid.Row,下面是一个使用MVVM、的简单示例

查看

<Window x:Class="WpfApplication3.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
 <Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="20"/>
        <RowDefinition Height="20"/>
        <RowDefinition Height="20"/>
    </Grid.RowDefinitions>
    <TextBlock Text="Hello" Grid.Row="{Binding RowNumber}"></TextBlock>
 </Grid>
</Window>

ViewModel

public class ViewModel
{
    public ViewModel()
    {
        RowNumber = 2;
    }
    public int RowNumber { get; set; }
}

我已将DataContext设置为从CodeBehind查看。如下所示,哪个DataContext链接到ViewModel类。我们可以用不同的方式设置CCD_ 10。

xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModel();    
    }
}

启动应用程序时,它会将RowNumber设置为2,并在第3行显示TextBlock。稍后,您可以通过从ViewModel 更新RowNumber来更改行