2012-07-31 52 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(); 
} 
相关问题