gpt4 book ai didi

c# - 将属性注册为 DependencyProperty

转载 作者:行者123 更新时间:2023-11-30 14:31:45 27 4
gpt4 key购买 nike

我有一个名为 ChartView 的用户控件。我有一个 ObservableCollection 类型的属性。我在 ChartView 中实现了 INotifyPropertyChanged。

ChartEntry 的代码是:

public class ChartEntry
{
public string Description { get; set; }
public DateTime Date { get; set; }
public double Amount { get; set; }
}

现在我想在另一个 View 中使用此控件并通过 DataBinding 为 ChartEntries 设置 ObservableCollection。如果我尝试这样做:

<charts:ChartView ChartEntries="{Binding ChartEntriesSource}"/>

我在 xaml 窗口中收到一条消息,提示我无法绑定(bind)到非依赖属性或非依赖对象。

我尝试将 ObservableCollection 注册为 DependencyProperty,但没有成功。我用 WPF Tutorial 中的代码进行了尝试

我的附加属性代码是

 public static class ChartEntriesSource
{
public static readonly DependencyProperty ChartEntriesSourceProperty =
DependencyProperty.Register("ChartEntriesSource",
typeof(ChartEntry),
typeof(ChartView),
new FrameworkPropertyMetadata(OnChartEntriesChanged));

private static void OnChartEntriesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{

}

public static void SetChartEntriesSource(ChartView chartView, ChartEntry chartEntries)
{
chartView.SetValue(ChartEntriesSourceProperty, chartEntries);
}

public static ChartEntry GetChartEntriesSource(ChartView chartView)
{
return (ChartEntry)chartView.GetValue(ChartEntriesSourceProperty);
}
}

这也没有用。如何将我的属性注册为 DependencyProperty?

最佳答案

您似乎对 AttachedPropertyDependencyProperty 感到有些困惑。忘掉您的 ChartEntriesSource 类...相反,将此 DependencyProperty 添加到您的 ChartView 控件中应该可以解决问题:

public static readonly DependencyProperty ChartEntriesProperty = DependencyProperty.
Register("ChartEntries", typeof(ObservableCollection<ChartEntry>), typeof(ChartView));

public ObservableCollection<ChartEntry> ChartEntries
{
get { return (ObservableCollection<ChartEntry>)GetValue(ChartEntriesProperty); }
set { SetValue(ChartEntriesProperty, value); }
}

关于c# - 将属性注册为 DependencyProperty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19542156/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com