2015-11-18 140 views
0

我新的WPF數據綁定和想不出它如何從我的視圖模型更新屬性WPF數據綁定的自定義屬性不更新

我有一個類命名爲患者

public string FirstName { get; set; } = ""; 
public string MiddleName { get; set; } = ""; 
public string LastName { get; set; } = ""; 

更新給病人類工作

private Data.Patient patient; 
public Data.Patient Patient 
{ 
    get { return patient; } 
    set 
    { 
      patient = value; 
      NotifyPropertyChanged("Patient"); 
    } 
} 

這不是由患者類更新我的視圖模型屬性

public string FullName 
{ 
    get { return Patient.LastName + " " + Patient.FirstName + " " + Patient.MiddleName; } 
} 

我試圖更新TextBlock的Text屬性

<TextBlock Text="{Binding FullName}" FontSize="14.667" /> 

如何從類更新適用於我的FullName屬性?我重新運行應用程序時會應用更新。

非常感謝

+0

也許你應該閱讀一些像這樣的文章 - http://blog.scottlogic.com/2012/04/05/everything-you-wanted-to-know-about-databinding-in-wpf-silverlight-and -wp7部分酮。html這裏的問題是,你不通知用戶界面FullName已經改變。我建議你要做的是爲你的名字屬性(FirstName,LastName ...)創建一個後臺字段,並在setter中將值賦給後臺字段後,調用NotifyPropertyChanged(「FullName」) – NValchev

+0

好的,謝謝@NValchev ,我會研究它。 – Chan

回答

1

你的問題是你不通知Fullname屬性已更改UI。從技術上講,它並沒有改變,但它依賴於其他一些財產。

這裏最簡單的解決方案是引發所有屬性的NotifyProperty事件。你不會寫很多代碼,只是通過nullNotifyPropertyChanged();

private Data.Patient patient; 

public Data.Patient Patient 
{ 
    get { return patient; } 
    set 
    { 
      patient = value; 
      NotifyPropertyChanged(null); //informs view that all properties updated 
    } 
} 

它會告訴你的模型,所有屬性已被更新。

MSDN:

PropertyChanged事件可以指示對象 在所有屬性都通過使用空值或的String.Empty作爲PropertyChangedEventArgs屬性名 改變。

0

更改從Text="{Binding FullName}"您結合Text="{Binding FullName, Mode="OneWay", UpdateSourceTrigger="PropertyChanged"}"應該觸發的PropertyChanged的事件。

0

NotifyPropertyChanged(...)一樣Patient屬性,您必須通知,當屬性全名已更改。要做到這一點,請在三個屬性的設置器中調用NotifyPropertyChanged("FullName"):FirstName,MiddleName和LastName。

也可以考慮,即NotifyPropertyChanged可能是零,因此使用:

if (NotifyPropertyChanged != null) 
    NotifyPropertyChanged("FullName"); 
0

我似乎無法使其工作。我將該屬性添加到我的類中,以便對該類進行的任何更改都會通知用戶界面,但仍然不能按我想要的方式工作。 但我找到了一個解決方案。

<TextBlock FontSize="14.667"> 
    <TextBlock.Text> 
      <MultiBinding StringFormat=" {0} {1} {2}"> 
       <Binding Path="Patient.LastName" /> 
       <Binding Path="Patient.FirstName"/> 
       <Binding Path="Patient.MiddleName"/> 
      </MultiBinding> 
    </TextBlock.Text> 
</TextBlock> 

感謝您的幫助。