0

我有这个DataGrid

<DataGrid x:Name="dgTimeline" Focusable="False" GotFocus="dgTimeline_GotFocus">

所以我添加了一个名为自定义类的列,TimelineControl并将其Minutes属性绑定到Time%

for (int i = 0; i <= 30; i++)
{
    FrameworkElementFactory fef = new FrameworkElementFactory(typeof(TimelineControl));
    Binding bTemp = new Binding("Time" + i);
    bTemp.Mode = BindingMode.TwoWay;
    fef.SetValue(TimelineControl.MinutesProperty, bTemp);
    DataTemplate dt = new DataTemplate();
    dt.VisualTree = fef;
    dgTempCol.CellTemplate = dt;

    dgTimeline.Columns.Add(dgTempCol);
}

这里是TimelineControl

public static DependencyProperty MinutesProperty =
DependencyProperty.Register("Minutes", typeof(string), typeof(TimelineControl),
new PropertyMetadata(OnMinutesChanged));

public string Minutes
{
    get { return (string)GetValue(MinutesProperty); }
    set { SetValue(MinutesProperty, value); }
}

private static void OnMinutesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    Console.WriteLine("foo bar");
}

稍后我添加了一些行:

TimeScale temp;
temp = this.addEvent(temp, 23);
temp = this.addEvent(temp, 24);
temp = this.addEvent(temp, 25);
temp = this.addEvent(temp, 26);

dgTimeline.Items.Add(temp);

private TimeScale addEvent(TimeScale temp, int time)
{
    PropertyInfo propertyInfo = temp.GetType().GetProperty("Time" + (time / 60));

    if (propertyInfo.GetValue(temp, null) != null)
    {
        if (propertyInfo.GetValue(temp, null).ToString().IndexOf((time % 60).ToString()) == -1)
        {
            propertyInfo.SetValue(temp, Convert.ChangeType(propertyInfo.GetValue(temp, null) +
                "," + (time % 60), propertyInfo.PropertyType), null);
        }
    }
    else
    {
        propertyInfo.SetValue(temp, Convert.ChangeType(time % 60, propertyInfo.PropertyType), null);
    }

    return temp;
}

到目前为止一切正常,OnMinutesChanged触发得很好,UI 也更新了。问题是,当我尝试更新某些内容时,DataGrid不会OnMinutesChanged触发并且 UI 不会更新。

我的目标OnMinutesChanged是手动更新已更改的特定元素的 UI。如果我打电话dgTimeline.Items.Refresh(),那么整个网格都会刷新并且一切正常,OnMinutesChanged就会被调用。问题是这个网格每秒更新一次,所以调用dgTimeline.Items.Refresh()使应用程序几乎冻结,因为元素数量很多(很容易超过 500 个)。我只需要每秒更新 3 个元素的 UI,而不是全部 500 个,这就是我要手动执行此操作的原因。

我在做正确的事吗?如果是,为什么OnMinutesChanged在我更新网格时没有被调用?

4

1 回答 1

2

DataGrid使用绑定组来验证整行并防止基础对象中的无效状态,以防其中一个属性被分配了无效值。这会将单元格内的默认UpdateSourceTrigger绑定更改为,您可以通过在绑定对象上Explicit显式设置它来覆盖它。PropertyChanged

通常,如果用户完成对一行的编辑,则会调用更新,但是您永远不会像使用时那样进入编辑模式,CellTemplate而不是CellEditingTemplate.

于 2013-05-27T15:49:41.243 回答