簡體   English   中英

XAML綁定未更新

[英]XAML Binding not updated

我在UWP中有一個用戶控件,我將其放在其他用戶控件中,這些用戶控件具有綁定到VM的兩個文本TextBlock。

這是XAML代碼:

數據上下文

DataContext="{Binding BalanceView, Source={StaticResource CoreModule}}"


<TextBlock Text="{Binding TotalBalance, Mode=TwoWay, Converter={StaticResource AmountFormatConverter}, UpdateSourceTrigger=PropertyChanged}"
           Style="{StaticResource DeemphasizedBodyTextBlockStyle}"
           Margin="0,0,5,0" />
<TextBlock Text=" / "
           Style="{StaticResource DeemphasizedBodyTextBlockStyle}"
           Margin="0,0,5,0" />
<TextBlock Text="{Binding EndOfMonthBalance, Mode=TwoWay, Converter={StaticResource AmountFormatConverter}, UpdateSourceTrigger=PropertyChanged}"
           Style="{StaticResource DeemphasizedBodyTextBlockStyle}"
           Margin="0,0,5,0" />

並且VM屬性在那里綁定到:

public double TotalBalance
{
    get { return totalBalance; }
    set
    {
        if (Math.Abs(totalBalance - value) < 0.01) return;

        totalBalance = value;
        RaisePropertyChanged();
    }
}

public double EndOfMonthBalance
{
    get { return endOfMonthBalance; }
    set
    {
        if (Math.Abs(endOfMonthBalance - value) < 0.01) return;

        endOfMonthBalance = value;
        RaisePropertyChanged();
    }
}

public event PropertyChangedEventHandler PropertyChanged;

/// <summary>
/// Raises this object's PropertyChanged event.
/// </summary>
/// <param name="propertyName">The property that has a new value.</param>
protected void OnPropertyChanged(string propertyName)
{
    PropertyChangedEventHandler handler = this.PropertyChanged;
    if (handler != null)
    {
        var e = new PropertyChangedEventArgs(propertyName);
        handler(this, e);
    }
}

我可以看到返回的值是正確的。 但是在UI上它永久為0。如果我將值靜態設置為一個值,它將正確顯示。

怎么了?

我懷疑您有這些雙重值作為私有屬性,在此處未顯示,但被引用為例如“ totalBalance”與PUBLIC“ TotalBalance”,並且與“ endOfMonthBalance”與“ EndOfMonthBalance”類似,否則它將無法編譯。

另外,您的RaisePropertyChanged()調用RaisePropertyChanged(“ TotalBalance”)和RaisePropertyChanged(“ EndOfMonthBalance”)而不是通過無參數調用。

調用OnPropertyChanged ,將CLR屬性的名稱作為參數傳遞。

private double totalBalance=0;   
public double TotalBalance
{
    get { return totalBalance; }
    set
    {
        if (Math.Abs(totalBalance - value) < 0.01) return;

        totalBalance = value;
        OnPropertyChanged("TotalBalance");
    }
}

private double endOfMonthBalance=0;
public double EndOfMonthBalance
{
    get { return endOfMonthBalance; }
    set
    {
        if (Math.Abs(endOfMonthBalance - value) < 0.01) return;

        endOfMonthBalance = value;
        OnPropertyChanged("EndOfMonthBalance");
    }
}

public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(String info)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(info));
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM