0

First of all, let me apologize for the super-noob question about WPF and binding. I have started, a few days ago, to get interested in WPF and its implementation with XAML markup and C# code-behind in Visual Studio Express 2013, and I'm trying to bind the contents of a button to a property that is part of a singleton class. And I can't, apparently.

What I want to do is this: I have a button saying "Start" and I want, on click, to have the button contents change to a timer + stop, something like "00:00:02 -- Stop" and, on click again, to have it change back to "Start".

I have this class that I have designed as a singleton to prevent it from being instantiated more than once, which contains an instance stopwatch of System.Diagnostics.Stopwatch, and a string property which I change either to "Start" or stopwatch.Elapsed.TotalSeconds.ToString () + "Stop" back and forth.

The problem is that when I try to refer to my singleton class in the XAML markup, like so (to be honest, I don't really know what I'm doing, I'm just inspiring myself from diverse examples I've found over the web):

<Window
    ...
    xmlns:local="clr-namespace:myNameSpace">

    <Grid>
        <local:mySingleton x:Key="myStringProperty" />
        ...
    </Grid>
</Window>

I get a slew of compiler errors (6 total) of which some say: "The type mySingleton does not include any accessible constructors." and "The "Key" attribute can only be used on an element that is contained in "IDictionary"."

I'm clueless as to what to do, knowing that I don't want to make the constructor public (and therefore get rid of the singleton thing).

Any pointers towards the right direction ?

Thank you guys for your help.

ReinaDelSur
  • 99
  • 1
  • 10
  • Get rid of the singleton. Not because of XAML problems but because chances are, it's the wrong pattern. Why do you need it to be a singleton? A Singleton will break all unit tests you have. – nvoigt Jul 30 '14 at 13:24

1 Answers1

0

At first you have problem in displaying your string property. You have to use text box and then use property for text binding:

<TextBox Text="{Binding Path=myStringProperty}"/>

Also you have to set your class (view model) to the Window.DataContext and your property have to call OnPropertyChanged event (see: WPF: simple TextBox data binding).

Now about singleton. The singleton shouldn't be used for this. You should have window (view) and that window have to work with some class (view model, you have one instance per one window) and if you want to run more windows together and you always want same result, then inside that view model you should have some static object (it can be that timer, or some class which will handle requests about get result from timer which will inside that class what can be singleton). So it could looks like Window (view) -> view model class -> static timer / class which will works with timer inside itself.

Community
  • 1
  • 1
Honza Kovář
  • 704
  • 6
  • 9