2015-09-27 14 views
1

我有一個XML文件,其中包含,除其他事項:如何綁定到這個字典條目?

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

該數據被讀入到這樣的字典:

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); 

然後我有這樣的C#代碼(除其他東西它):

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

現在我需要一個XAML文本標籤綁定到一個單位元素是這樣的:

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

它認爲質量是一個意外的令牌,和

DataContext未設置爲格式化程序而是ViewModel,btw。

問題:綁定看起來像什麼? (該XAML應顯示 「公斤」。)

+1

爲什麼不創建ObservableCollection的單位?字典根本不適合綁定。 – Spawn

+0

我會使用ValueConverter來獲取字典元素 – thumbmunkeys

回答

2

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> 

視圖模型:

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

    public MyViewModel() 
    { 
     MyFormatter = new 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 }); 
    } 
} 

單位:

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

enter image description here