我有一個UserControl,它以星星的數量顯示評級。它通過將 TextBlock 的 Text 屬性系結到常規代碼后臺屬性來實作這一目的,而該屬性又使用了一個整數 DependencyProperty Value。
為了在Value變化時更新 TextBlock,我需要從 DependencyProperty 的 PropertyChangedCallback 中手動觸發 INotifyPropertyChanged.PropertyChanged 事件。
這讓人感覺太過分了。是否有更簡單的方法來實作這一目標?
< TextBlock Text="{Binding RatingDisplay, Mode=OneWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x: Type local:Rating}}" />
public partial class Rating : UserControl, INotifyPropertyChanged :.
{
public static readonly DependencyProperty ValueProperty =
DependencyProperty. Register("Value", typeof(int), typeof(Rating), new PropertyMetadata(0, (sender, e) =>
{
((Rating)sender).RaisePropertyChanged(nameof(RatingDisplay) )。
}));
public Rating()。
{
InitializeComponent()。
}
public event PropertyChangedEventHandler? PropertyChanged。
public int Value
{
get => (int)GetValue(ValueProperty)。
set => SetValue(ValueProperty, value) 。
}
public string RatingDisplay => new string('*'/span>, Value)。
protected void RaisePropertyChanged(string? propertyName = null)?
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName))。
uj5u.com熱心網友回復:
你不需要在暴露依賴屬性的類中實作INotifyPropertyChanged。依賴屬性提供了他們自己的變更通知機制。
為了更新一個只讀的依賴屬性,類似這樣的做法應該是可行的:
public partial class Rating 。UserControlprivate static readonly DependencyPropertyKey RatingDisplayPropertyKey =
DependencyProperty.RegisterReadOnly(
nameof(RatingDisplay), typeof(string), typeof(Rating), null)。)
public static readonly DependencyProperty RatingDisplayProperty =
RatingDisplayPropertyKey.DependencyProperty。
public static readonly DependencyPropertyValueProperty =
樣式和顏色。
nameof(Value), typeof(int), typeof(Rating)。
new PropertyMetadata(0, (o, e) => o.SetValue(
RatingDisplayPropertyKey, new string('*'/span>, (int)e.NewValue))));
public Rating()
{
InitializeComponent()。
}
public int Value
{
get => (int)GetValue(ValueProperty)。
set => SetValue(ValueProperty, value) 。
}
public string RatingDisplay => (string)GetValue(RatingDisplayProperty)。
}
另外,用一個系結轉換器系結Value屬性,從Rating Value中創建一個字串。
或者,可能是最簡單的,直接訪問應該更新的UI元素:
<TextBlock x:Name="ratingDisplay"/span>/>
后面有這樣的代碼:
public partial class Rating : UserControlpublic static readonly DependencyPropertyValueProperty =
樣式和顏色。
nameof(Value), typeof(int), typeof(Rating)。
new PropertyMetadata(0, (o, e) =>
((Rating)o).ratingDisplay.Text = new string('*', (int)e.NewValue) )。
public Rating()
{
InitializeComponent()。
}
public int Value
{
get => (int)GetValue(ValueProperty)。
set => SetValue(ValueProperty, value) 。
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/307899.html
標籤:
