我的自定义控件出现问题。当我提出通知属性改变时,我的财产的获取者从未被调用。我已经四处搜索了,我不认为我打破了我的约束力(尽管我可能错了)。
我的控制如下:
XAML
<UserControl x:Class="ClassNamespace.ClassName"
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:mui="http://firstfloorsoftware.com/ModernUI"
xmlns:default="clr-namespace:PullTabs.Applications.FrontEnd.Views.Default"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="Sample Text" />
<DataGrid Grid.Row="1" FontSize="20" ItemsSource="{Binding Bills, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type default:ClassName}}}" />
<TextBlock Text="Sample Text" />
</Grid>
背后的代码是:
public partial class ClassName
{
public static DependencyProperty TransactionsProperty = DependencyProperty.Register("Transactions",
typeof (IEnumerable<Transaction>), typeof (BillCounts),
new UIPropertyMetadata(new List<Transaction>(), OnTransactionsPropertyPropertyChangedCallback));
private static void OnTransactionsPropertyPropertyChangedCallback(DependencyObject source,
DependencyPropertyChangedEventArgs e)
{
UpdateBillCounts((IEnumerable<Transaction>) e.NewValue);
}
public static ObservableCollection<Bill> Bills { get; } = new ObservableCollection<Bill>();
public IEnumerable<Transaction> Transactions
{
get { return (IEnumerable<Transaction>) GetValue(TransactionsProperty); }
set { SetValue(TransactionsProperty, value); }
}
public BillCounts()
{
InitializeComponent();
}
private static void UpdateBillCounts(IEnumerable<Transaction> transactions)
{
var lifetimeBillsAccepted = new Dictionary<decimal, int>();
Bills.Clear();
foreach (var bill in transactions)
{
if (lifetimeBillsAccepted.ContainsKey(bill.Amount))
{
lifetimeBillsAccepted[bill.Amount] = lifetimeBillsAccepted[bill.Amount] + 1;
}
else
{
lifetimeBillsAccepted.Add(bill.Amount, 1);
}
}
foreach (var bill in lifetimeBillsAccepted)
{
Bills.Add(new Bill($"{bill.Key:C2}", bill.Value));
}
Bills.Add(new Bill("Total", Bills.Sum(bill => bill.Count)));
}
}
它的使用方式如下:
<Default:BillCounts Grid.Column="0" Margin="0,10" Transactions="{Binding PeriodTransactions}" />
PeriodTransactions的定义如下:
public IEnumerable<Transaction> PeriodTransactions
{
get
{
_periodTransactions = _periodTransactions ?? GetMyDataFromDB();
return _periodTransactions;
}
}
其中PeriodTransactions是一个有效的只读属性,包含依赖项属性的有效数据。
当我点击一个按钮并触发它的方法时,我运行以下两行代码:
_periodTransactions = GetMyDatFromDB();
RaisePropertyChanged(nameof(PeriodTransactions));
我希望PeriodTransactions属性的getter然后执行,因为我显式调用了名为PeriodTransactions属性的属性change方法。但是,在getter中设置了断点,只有在创建视图时才会调用它,而不会再次调用。请提供一些见解,了解我的自定义控件中的依赖项属性为何不更新,或者为什么getter不会被我的自定义控件的依赖项属性调用。