简体   繁体   中英

WPF binding works only once

I'm developing a C# project in which I've to use WPF and I'm encountering some problems with binding dynamic content to UI.

Briefly, I have this textBlock here declared in a file called NotifyIconResources.xaml:

<TextBlock Name="label_stato" Text="{Binding Source={x:Static Application.Current}, Path=Properties[status]}"/>

It shows the value of a string property, called status, declared in App.xaml.cs:

public partial class App : Application, INotifyPropertyChanged
{
    private MainWindow mw;

    private TaskbarIcon notifyIcon;

    public event PropertyChangedEventHandler PropertyChanged;

    private string _status;
    private string status
    {
        get
        {
            return _status;
        }
        set
        {
            _status = value;
            NotifyPropertyChanged("status");
        }
    }

    /// <summary>
    /// Triggers a GUI update on a property change
    /// </summary>
    /// <param name="propertyName"></param>
    private void NotifyPropertyChanged(string propertyName = "")
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        this.Properties["status"] = "Online";

        //create the notifyicon (it's a resource declared in NotifyIconResources.xaml
        ResourceDictionary rd = new ResourceDictionary
        {
            Source = new Uri("/NotifyIconResources.xaml", UriKind.RelativeOrAbsolute)
        };
        notifyIcon = (TaskbarIcon)rd["NotifyIcon"];

        mw = new MainWindow(Environment.GetCommandLineArgs()[1]);
        mw.Show();
    }
}

The value of the property is dynamic, its initial value is showed in the textBlock, but the next modifications of its value don't result in a refresh of the textBlock content.

NotifyIconResources.xaml is declared in App.xaml:

<Application x:Class="FileSharingOnLAN.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:local="clr-namespace:FileSharingOnLAN"
         StartupUri="MainWindow.xaml"
         ShutdownMode="OnExplicitShutdown">
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="NotifyIconResources.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>
<Application.MainWindow>
    <NavigationWindow Source="MainWindow.xaml" Visibility="Visible"></NavigationWindow>
</Application.MainWindow>

The NotifyIconResources.xaml file:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:local="clr-namespace:FileSharingOnLAN"
                xmlns:tb="http://www.hardcodet.net/taskbar">

<tb:TaskbarIcon x:Key="NotifyIcon"
                IconSource="/Red.ico"
                ToolTipText="Click for popup, right-click for menu"
                ContextMenu="{StaticResource SysTrayMenu}">
    <tb:TaskbarIcon.TrayPopup>
        <Border
            Background="Black"
            Width="200"
            Height="100">
            <StackPanel>
                <Button
                Content="{Binding ButtonContent}"
                VerticalAlignment="Top"
                Command="{Binding ShowImpostazioniWindowCommand}"/>
                <Border
                    Background="Blue"
                    Width="100"
                    Height="50"
                    VerticalAlignment="Bottom"
                    HorizontalAlignment="Left">
                    <StackPanel>
                        <Label                
                            Content="Stato" />
                        <!--<Button
                            Content="{Binding Path="status", Source="{x:Static Application.Current}"}"
                            Command="{Binding StatusClickedCommand}"/>-->
                        <TextBlock Name="label_stato" Text="{Binding Source={x:Static Application.Current}, Path=Properties[status]}"/>
                    </StackPanel>
                </Border>
            </StackPanel>
        </Border>
    </tb:TaskbarIcon.TrayPopup>

    <tb:TaskbarIcon.DataContext>
        <local:NotifyIconViewModel />
    </tb:TaskbarIcon.DataContext>
</tb:TaskbarIcon>

I've tried to fix it by using OnpropertyChanged, like in this: Binding to change the property but it didn't work.

In the same project I use other binding techniques which work and I know how to solve this problem programmatically but I want to understand where my error is, I'm totally stuck with it.

You have few things that needs to be changed:

First one is status property it self, make it public:

public string Status
{
    get
    {
        return (string)this.Properties["status"];
    }
    set
    {
        this.Properties["status"] = value;
        NotifyPropertyChanged("Status");
    }
}

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
    Status = "Online";
    ...
}

And change your binding to:

<TextBlock Text="{Binding Source={x:Static Application.Current}, Path=Status}" />

Working Example:

<Window x:Class="WpfApplicationTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplicationTest"
        mc:Ignorable="d"
        x:Name="win"
        Title="MainWindow" Height="300" Width="300">
    <Window.Resources>
    </Window.Resources>
    <StackPanel FocusManager.FocusedElement="{Binding ElementName=btnDefault}">
        <TextBox Text="{Binding Source={x:Static Application.Current}, Path=Status}" />
        <TextBlock Text="{Binding Source={x:Static Application.Current}, Path=Status}" />
        <Button>Button 7</Button>
    </StackPanel>
</Window>

Found a working solution.

I was changing the value of the property in another cs module like this:

Application.Current.Properties["status"] = "Offline";

This line cannot result in a modification of the property, so I wasn't modifying it. So, thanks to https://stackoverflow.com/a/1609155/10173298 , I solved it by substituting that line with:

((App)Application.Current).setOffline();

Where setOffline() is a method I've added to App.xaml.cs:

public void setOffline()
{
    this.Status = "Offline";
}

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