bircastri
bircastri

Reputation: 153

How to use DynamicResource of Label content?

I try to development a WPF application with "DynamicResource", so I have i Label in XAML file like this:

   <Window.Resources>
        <local:BindingClass x:Key="myDataSource"/>
        <local:UtilityGioco x:Key="myUtilityGame"  />
    </Window.Resources>

   <Label x:Name="labelTempo" DataContext="{DynamicResource myUtilityGame}" Content="{Binding Path=tempoEsecuzioneEsercizio}" FontFamily="Arial" FontSize="21" 
                           Foreground="Gray" Grid.Column="0" Grid.Row="1" FontWeight="Bold"
                           Margin="15,40,0,0"/>

In the UtilityGioco class i have this code:

public string tempoEsecuzioneEsercizio
{
    set;
    get;
}

private void displayTimer(object sender, EventArgs e)
{
    try
    {
        // code goes here
        //Console.WriteLine(DateTime.Now.Hour.ToString() + ":"); 
        if (timeSecond == 59)
        {
            timeSecond = 0;
            timeMinutes++;
        }
        //se il contatore dei minuti è maggiore di 0, devo mostrare una scritta altrimenti un altra
        if (timeMinutes > 0)
        {
            tempoEsecuzioneEsercizio = timeMinutes + " min " + ++timeSecond + " sec";
        }
        else
        {
            tempoEsecuzioneEsercizio = ++timeSecond + " sec";
        }
    }
    catch (Exception ex)
    {
        log.Error("MainWindow metodo: displayTimer ", ex);
    }
}

The "displayTimer" method is called every time, but the content of Label is blank.

Can you help me?

Upvotes: 0

Views: 800

Answers (2)

pask23
pask23

Reputation: 734

Maybe you can use INotifyPropertyChanged:http://msdn.microsoft.com/it-it/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx

public event PropertyChangedEventHandler PropertyChanged;
private string _tempoEsecuzioneEsercizio;
public string tempoEsecuzioneEsercizio
{
    set 
    {

      if (_tempoEsecuzioneEsercizio != value)
      {
        this._tempoEsecuzioneEsercizio = value;
        this.OnNotifyPropertyChange("tempoEsecuzioneEsercizio");
      }         
    }

    get { return _tempoEsecuzioneEsercizio; }
}


public void OnNotifyPropertyChange(string propertyName)
{
  if (this.PropertyChanged != null)
  {
    this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
  }
}

Upvotes: 1

BlueM
BlueM

Reputation: 6888

In your UtilityGioco class implement INotifyPropertyChanged interface and notify about the change in the setter of tempoEsecuzioneEsercizio property.

Example:

private string _tempoEsecuzioneEsercizio;
public string tempoEsecuzioneEsercizio
{
    set 
    {
      _tempoEsecuzioneEsercizio = value;
      if (PropertyChanged != null)
      {
        PropertyChanged(this, new PropertyChangedEventArgs("tempoEsecuzioneEsercizio"));
      }         
    }

    get { return _tempoEsecuzioneEsercizio; }
}

Upvotes: 2

Related Questions