Erik
Erik

Reputation: 954

How to bind to this dictionary entry?

I have an XML file, containing, among other things:

<Unit Name="Mass" Factor="1" Display="kg"/>
<Unit Name="MassPU" Factor="0.001" Display="kg/m"/>

This data is read into a dictionary like this:

Formatter.Units = (data.Descendants("Unit").Select(x => new Unit
          (
           x.Attribute("Name").Value,
           x.Attribute("Display").Value,
           Convert.ToDouble(x.Attribute("Factor").Value)
          )
       ) ToList()).ToDictionary(x => x.Name, x => x);

Then I have C# code like this (among other stuff in it):

namespace mySpace
{  
    public static class Formatter
    {
       public enum MUnits {Mass = 0, Force, .... etc };
        public static Dictionary<string, Unit> Units { get; set; } 
    }
}

Now I need to bind a XAML text label to a Units element something like this:

<Label         
     Content="{Binding Source={x:Static c:Formatter.Units[Mass].Display}}"/>

It thinks Mass is an unexpected token, and the . too.

The DataContext is not set to Formatter but to ViewModel, btw.

Question: what must the binding look like? (The XAML should display "kg".)

Upvotes: 1

Views: 83

Answers (1)

jsanalytics
jsanalytics

Reputation: 13188

XAML:

<Window.DataContext>
    <local:MyViewModel/>
</Window.DataContext>
<Grid>
    <Label x:Name="label1"  Content="{Binding MyFormatter[Mass].Display}" Width="300" FontSize="18.667" Margin="95,10,123.4,232.8"/>
    <Label x:Name="label2"  Content="{Binding MyFormatter[MassPU].Display}" Width="300" FontSize="18.667" Margin="95,93,123.4,157.8"/>
</Grid>

ViewModel:

public class MyViewModel
{
    public Formatter MyFormatter { get; set; }

    public MyViewModel()
    {
        MyFormatter = new Formatter();
    }
}

Formatter:

public class Formatter : Dictionary<string, Unit>
{
    public Formatter()
    {
        Add("Mass", new Unit { Name = "Mass", Display = "Kg", Factor = 1 });
        Add("MassPU", new Unit { Name = "MassPU", Display = "Kg/m", Factor = 0.001 });
    }
}

Unit:

public class Unit
{
    public string Name { get; set; }
    public string Display { get; set; }
    public double Factor { get; set; }
}

enter image description here

Upvotes: 2

Related Questions