2012-07-31 56 views
0

背景:是否可以使用XAML中的服務接口,而不是代碼隱藏?

我有我的看法,我用它來從不同的語言文字得到的一個LabelService類的實例。

這就要求我的代碼在後臺如下填充在TextBlock中文字:

XAML:

<TextBlock Name="txtExample" Grid.Row="0" Margin="5,5,5,5"/> 

C#:

// 'this' refers to the current class, the namespace of which is used to navigate 
// through an XML labels file to find the correct label 
string label = _labelService.GetSpecificLabel(this, txtExample.Name).Label 
txtExample.Text = label; 

問題:

是否有可能我h此功能:

_labelService.GetSpecificLabel(this, txtExample.Name).Label 

可在XAML?

補充信息:

只是爲了解釋什麼,我使用命名空間導航標籤XML的意思是:

假設類的定義如下,在命名空間

namespace My.App.Frontend 
{ 
    public class MainWindow 
    { 
     string label = _labelService.GetSpecificLabel(this, txtExample.Name).Label 
    } 
} 

相應的XML將是

<My> 
    <App> 
    <Frontend> 
     <MainWindow> 
      <txtExample label="I am the example text" /> 
     </MainWindow> 
    </Frontend> 
    </App> 
</My> 

回答

1

在WPF中,MVVM模式通常用於實現此目的。

在後面的代碼中執行此操作甚至被認爲是不好的做法,因爲它不可測試且不可維護。 將代碼隱藏爲儘可能空。

這樣,您就有了一個ViewModel類,它可以連接到您的 標籤服務。然後,您的視圖綁定到ViewModel。

這裏是如何構建一個WPF應用程序很好的視頻教程: Jason Dollinger on MVVM

他在教程中開發的源代碼也可以在這裏: Source code of Jason Dollinger

這是一個非常簡單的視圖模型對你來說,只是爲了讓你有一個起點: (注意_labelService和txtExample不會在此刻設置有)

public class TextBoxViewModel : INotifyPropertyChanged 
{ 
    public TextBoxViewModel() 
    { 
     string label = _labelService.GetSpecificLabel(this, txtExample.Name).Label; 
     this.text = label; 
    } 

    private string text; 

    public string Text 
    { 
     get 
     { 
      return text; 
     } 

     set 
     { 
      text = value; 
      NotifyPropertyChanged("Text"); 
     } 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 

    private void NotifyPropertyChanged(string propertyName) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 
} 

在XAML中,綁定部分是很重要的:

<TextBox Text="{Binding Text}" Height="26" HorizontalAlignment="Left" Margin="77,215,0,0" Name="textBox1" VerticalAlignment="Top" Width="306" /> 

在代碼隱藏(或更好:在這裏你做你的腳手架)

public MainWindow() 
{ 
    InitializeComponent(); 

    this.DataContext = new TextBoxViewModel(); 
} 
相關問題