2012-12-25 81 views
2

我想显示多个ComboBox es中的相同ComboBoxItem s。多个组合框的相同内容

<ComboBox> 
    <ComboBoxItem Content="1" /> 
    <ComboBoxItem Content="2" /> 
    <ComboBoxItem Content="3" /> 
    <ComboBoxItem Content="4" /> 
    <ComboBoxItem Content="5" /> 
</ComboBox> 

有没有简单的方法来做到这一点,而不重复的代码,只有在XAML(不使用代码隐藏)?

回答

3

回答你的问题是的,你可以在Xaml中创建一个通用数组并将其分配给ComboBox的ItemsSource。它看起来像这样。这可以放在您的应用程序资源中,以实现全程可见性。

<Window x:Class="WpfApplication1.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:system="clr-namespace:System;assembly=mscorlib" 
    Title="MainWindow" Height="350" Width="525"> 
    <Window.Resources> 
     <x:ArrayExtension x:Key="myArray" Type="system:String"> 
      <system:String>1</system:String> 
      <system:String>2</system:String> 
      <system:String>3</system:String> 
      <system:String>4</system:String> 
      <system:String>5</system:String> 
     </x:ArrayExtension> 
    </Window.Resources> 
    <Grid> 
     <ComboBox Height="23" ItemsSource="{StaticResource myArray}" HorizontalAlignment="Left" Margin="10,10,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120" /> 
     <ComboBox Height="23" ItemsSource="{StaticResource myArray}" HorizontalAlignment="Left" Margin="148,10,0,0" Name="comboBox2" VerticalAlignment="Top" Width="120" /> 
    </Grid> 
</Window> 
0

简单 - 将Comboboxes数据绑定到相同的DataSource。


<ComboBox ItemsSource={Binding CommonItems} /> 

这将在窗口/用户控件的DataContext的搜索,该组合框是一个公共财产称为CommonItems的孩子,并用它作为一个的ItemSource。


快速样品:

如果你有一个WPF应用程序中的简单的窗口,在窗口后面的代码,你可以在构造函数中设置:

Window1() 
{ 
    this.DataContext = this; 
} 

之后,定义一个公共属性CommonItems,您可以在其中设置要在多个ItemsControl中使用的列表:

public List<string> CommonItems {get;set;} 

,并且在Window UI代码(xaml文件)中,您可以将CommonItems列表用作多个控件的ItemSource,它将起作用。

+0

如果你不知道如何使用数据绑定,什么是与DataContexts交易,你应该对一些教程阅读了,因为从我或其他人快速样品不会帮助你,因为你不会明白它为什么有效。快乐编码! – dutzu

+0

我会延长我的答案与更多信息... – dutzu

+0

我想这样做没有代码隐藏。 – Elmo

0
var priceList = new List<int> 
         { 
          1, 
          2, 
          3, 
          4, 
          5 
         }; 

    //Now we can use CopyTo() Method 

    priceList.CopyTo(insuredList); 


    ComboBox1.Datasource=priceList; 
    ComboBox2.Datasource=insuredList; 

//如果没有后面的方法的代码:

你需要为每个组合框创建新ComboBoxItems。通常你会使用一个源集合和bind这两个组合框,然后他们将自己创建新的项目。您可以使用application resources。将您自己的样式(模板)添加到全局资源中,可让您与多个控件共享它。