2015-12-21 63 views
1

我有一個文本框,如果文本框有Text.Length >0那麼我必須改變HasChar屬性True,否則False。在這裏,我無法綁定Setter中的屬性。如何根據條件將屬性從VIew模型綁定到DataTrigger設置器?

的XAML源代碼:

<TextBox Text="WPF"> 
    <TextBox.Style> 
     <Style TargetType="{x:Type TextBox}"> 
      <Style.Triggers> 
       <DataTrigger Value="0" 
        Binding="{Binding Text.Length, RelativeSource={RelativeSource Self}}"> 
        <Setter Property="{Binding HasChar}" Value="False" /> 
       </DataTrigger> 
      </Style.Triggers> 
     </Style> 
    </TextBox.Style> 
</TextBox> 

視圖模型C#源代碼:

private bool _hasChar= true; 
public bool HasChar 
{ 
    get { return _hasChar; } 
    set 
    { 
     _hasChar= value; 
     OnPropertyChanged(); 
    } 
} 
+0

數據觸發器可以在數據源到目標(可視元素)的情況下工作,而您正試圖將其反轉。 「TextBox.Text」是否綁定到相同視圖模型的某些屬性? – Dennis

+0

不,我沒有將任何屬性綁定到TextBox.Text。我需要綁定Setter中的屬性。請在這方面幫助我。 –

回答

3

你濫用觸發器。
正確的路要走:

1)XAML:

<TextBox Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}"/> 

2)視圖模型。你不需要添加setter到HasChar。如果這個屬性被綁定到的東西看來,只是適當提高PropertyChanged

public class ViewModel : INotifyPropertyChanged 
{ 
    // INPC implementation is omitted 

    public string Text 
    { 
     get { return text; } 
     set 
     { 
      if (text != value) 
      { 
       text = value; 
       OnPropertyChanged();      
       OnPropertyChanged("HasChar"); 
      } 
     } 
    } 
    private string text; 

    public bool HasChar 
    { 
     get { return !string.IsNullOrEmpty(Text); } 
    } 
} 
0

你不能在一個二傳手屬性綁定。樣式用於設置UI元素屬性,如文本,可視性,前景等。

相關問題