简体   繁体   中英

How to bind simple static string to WPF Label

I have a C# .NET 4.5 WPF application, with a public static class. Inside that class I have a public static string. What I want is very simple, I want to bind that static string to a WPF Label , so whenever that string is updated, WPF Label will also get updated.

How can I achieve this with simplest and easiest way

Static class below

public static class GlobalStats
{
    private static void updateValues()
    {
        srGlobalStatics="example";   
    }
    public static string srGlobalStatics = "";
}

I want my WPF Label bound to that particular srGlobalStatics string.

Here's my XAML code:

<Label Name="lblGlobalStats" Content="lblGlobalStats" HorizontalAlignment="Left"
       Margin="10,36,0,0" VerticalAlignment="Top"/>

Isn't this possible ?

I can write a function inside MainWindow.xaml.cs however i don't want to put unnecessary code inside there as much as possible.

Answer for your first post:

 <Label Name="lblGlobalStats" 
 Content="{Binding Source={x:Static wpfApplication1:GlobalStats.srGlobalStatics}}" 
 HorizontalAlignment="Left" Margin="10,36,0,0" VerticalAlignment="Top"/>

To your second question (raised in comments), assuming you want it all static (as ugly as it is):

public static void updateValues()
{
    srGlobalStatics[0] = "changed";
}

public static ObservableCollection<string> srGlobalStatics = 
   new ObservableCollection<string> { "test" };

Wpf:

<Label Name="lblGlobalStats" 
    Content="{Binding Path=[0], Source={x:Static 
    wpfApplication1:GlobalStats.srGlobalStatics}}" 
    HorizontalAlignment="Left" Margin="10,36,0,0" VerticalAlignment="Top"/>

The simplest (not necessarily the best) way to do this would be to declare your GlobalStats class as non-static, set it as your DataContext , and finally bind to your string from the XAML source:

public class GlobalStats
{
    private string _myLabel;

    public string MyLabel {
        get { return _myLabel; }
        set { _myLabel = value; }
    }
}

Then, in your code-behind, have something like this:

private GlobalStats_myDataModel = new GlobalStats();

// ...

public MainWindow() {
    // ...
    DataContext = _myDataModel;

Finally, your XAML:

<Label Name="lblGlobalStats" Content="{Binding Path=MyLabel" HorizontalAlignment="Left"
   Margin="10,36,0,0" VerticalAlignment="Top"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM