如何绑定附属财产

时间:2016-08-02 15:13:09

标签: c# wpf xaml data-binding

我正在尝试自己学习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>

以下是MainWindow的代码隐藏文件:

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>

1 个答案:

答案 0 :(得分:1)

可以绑定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>

<强>视图模型

public class ViewModel
{
    public ViewModel()
    {
        RowNumber = 2;
    }

    public int RowNumber { get; set; }
}

我已将DataContext设置为CodeBehind的视图。如下所示,DataContextViewModel类相关联。我们可以用不同的方式设置DataContext

<强> xaml.cs

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

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

中的ViewModel来更改行