绑定XAML中其他文件的内容

时间:2017-10-02 08:42:02

标签: c# wpf xaml

所以我计划从两个或更多文件中绑定标签,因为我以不同的方式放置标签和cs文件。例如:

SettingServicesPhone.xaml

<Label x:Name="sipLoginStatus"
  Width="106"
  Height="27"
  HorizontalAlignment="Left"
  VerticalAlignment="Top"
  Content="{Binding SipLoginStatusContent}"
  FontSize="13" />

对于SettingServicePhone.xaml.cs,我声明了public String sipLoginStatusContent;

我使用Settings.xaml和Setting.xaml.cs作为所有函数的容器。 我在public static SettingsServicesPhone setCall = new SettingsServicesPhone();上声明了Setting.xaml.cs。并写下get set

public String SipLoginStatusContent
{
    get { return setCall.sipLoginStatusContent; }
    set
    {
        if (setCall.sipLoginStatusContent != value)
        {
            setCall.sipLoginStatusContent = value;
            OnPropertyChanged("SipLoginStatusContent");  // To notify when the property is changed
        }
    }
}

这里是我在Settings.xaml.cs上说明的onclick按钮的例子

public void applyBtn_Click(object sender, RoutedEventArgs e)
{
   SipLoginStatusContent = "Logging In";
}

如果我将它们包含在一个文件中,它的工作正常。但是如果我把它分开的话似乎没有运行。我做错了吗?谢谢。

1 个答案:

答案 0 :(得分:0)

将定义DataContext的窗口的Label设置为定义SipLoginStatusContent属性的类的实例:

public partial class Settings : Window
{
    public static SettingsServicesPhone setCall = new SettingsServicesPhone();

    public Settings()
    {
        InitializeComponent();
        DataContext = this; //<--
    }

    public String SipLoginStatusContent
    {
        get { return setCall.sipLoginStatusContent; }
        set
        {
            if (setCall.sipLoginStatusContent != value)
            {
                setCall.sipLoginStatusContent = value;
                OnPropertyChanged("SipLoginStatusContent");  // To notify when the property is changed
            }
        }
    }

    public void applyBtn_Click(object sender, RoutedEventArgs e)
    {
        SipLoginStatusContent = "Logging In";
    }
}