2012-03-16 103 views
0

我在我的WPF项目中有一个组合框,我想让它在我的配置类中由只读字符串数组定义的项目。这样我可以很容易地重新配置组合框项目。是否可以将ComboBox ItemsSource绑定到只读字符串[]?

是否有可能将我的ItemsSource属性绑定到只读字符串[]?如何做到这一点?

+4

这是可能的。你有什么尝试? – Bernard 2012-03-16 18:08:48

+0

当然,我已经尝试过,但是我做不到。这就是为什么我想在这里得到一些帮助。你能发布代码吗? – jpnavarini 2012-03-16 18:11:09

回答

3

主窗口:

<Window x:Class="WpfApplication4.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="clr-namespace:WpfApplication4" 
    Title="MainWindow" Height="350" Width="525"> 
<StackPanel> 
    <ComboBox ItemsSource="{Binding List, Source={x:Static local:Configuration.Instance}}"></ComboBox> 
</StackPanel> 

配置文件:

public class Configuration 
{ 

    // Singleton    
    private static Configuration _instance; 
    public static Configuration Instance 
    { 
     get 
     { 
      if (_instance == null) 
       _instance = new Configuration(); 

      return _instance; 
     } 
    } 

    public IEnumerable<string> List 
    { 
     get 
     { 
      return new List<string>() 
      { 
       "toto 1", 
       "toto 2" 
      }; 
     } 
    } 

    public Configuration() 
    { 

    } 
} 
+0

绑定到枚举:http://stackoverflow.com/questions/878356/wpf-combobox-binding-to-enum-what-did-i-do-wrong – Jonas 2012-03-16 18:20:30

+0

你可以做到这一点没有单身的事情,例如如果List只是配置的静态属性? – 2013-09-10 10:03:57

+0

@LouisRhys也许尝试这样的:http://stackoverflow.com/a/3862828/1073409 – Jonas 2013-09-10 18:58:12

3

是,复制/粘贴/编译如下:

<ComboBox ItemsSource="Is it possible to Bind a ComboBox (WPF) ItemsSource to a read only string[]"/>