开发者

How to bind a Combobox ItemSource to a Property not in the DataContext?

开发者 https://www.devze.com 2023-03-20 05:11 出处:网络
I have a Dialog box, ConfigSetup that has a Combobox. Its data context is set to the viewModel, but I need to bind the ItemSource of my Combobox to a property in the main window( MainWindow).

I have a Dialog box, ConfigSetup that has a Combobox. Its data context is set to the viewModel, but I need to bind the ItemSource of my Combobox to a property in the main window( MainWindow).

   public partial class MainWindow : Window, INotifyPropertyChanged
   {
   ...
        public CfgData.TMicMode[] MicModeOptions
        {
            get
            {
                return (CfgData.TMicMode[])System.Enum.GetValues(typeof(CfgData.TMicMode));
            }
        }

   }

Here's where the viewModel is setup in the dialog box code

    public partial class ConfigSetup : Window, INotifyPropertyChanged
    {
        private ConfigSetupVM vm_ = null;
        public ConfigSetup(CfgData cfgData)
        {
            vm_ = new ConfigSetupVM(cfgData);

            InitializeComponent();

            vm_.RequestClose += delegate
            {
                Close();
            };


            DataContext = vm_;

        }
   }

Here's the code in the VM that has the selectedvalue property to bind to

   class ConfigSetupVM : ViewModelBase, IDataErrorInfo
    {
    ...

         /// <summary> 
        /// C-5000's microphone mode.
        /// </summary>/
        public CfgData.TMicMode MicMode
        {
            get { ret开发者_StackOverflowurn model_.MicMode; }
            set { model_.MicMode = value; NotifyPropertyChanged("MicMode"); }
        }

Here's the XAML with the combobox

<Window x:Class="RpP25.ConfigSetup"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:RpWin="clr-namespace:RpP25"
    Title="FCT Configuration" 
    Width="300"
    SizeToContent="Height"
    ResizeMode="NoResize"
    WindowStartupLocation="CenterOwner" WindowStyle="ToolWindow"
    FocusManager.FocusedElement="{Binding ElementName=name}"
    Background="AliceBlue" >
    <Window.Resources>
    ...
    </Window.Resources>
    ...

    <ComboBox Grid.Row="6" Grid.Column="1"
              HorizontalAlignment="Right" MinWidth="75"
              ItemsSource="{Binding RpWin:MainWindow.MicModeOptions, Mode=OneWay}"
              SelectedValue="{Binding RpWin:MainWindow.MicMode, Mode=TwoWay, TargetNullValue=Not Selected,
                                      ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True}" />


...

I know I'm missing something fundamental to Binding, but I can't for the life of figure out how to bind to something outside the datacontext.

I've tried to use FindAncestor... with no success

You help would be greatly appreciated.


There are two possible ways. The one is, as the code below, to use the static member.

<ComboBox ItemsSource="{Binding Source={x:Static local:MainWindow.MicModeOptions} , Mode=OneWay}"/>

public partial class MainWindow : Window, INotifyPropertyChanged
{

    public **static** CfgData.TMicMode[] MicModeOptions
    {
    }
}

The other is to use Resources in XAML, where the target class(MainWindow in your code) has to get a default constructor(parameterless).

<Grid>
    <Grid.Resources>
        <local:MainWindow x:Key="mainWindow"/>
    </Grid.Resources>
    <ComboBox ItemsSource="{Binding Source={StaticResource mainWindow}, Path=MicModeOptions , Mode=OneWay}"/>
</Grid>


How is the dialog window launched? If it is launched via window.ShowDialog() then you could pass the necessary object you need to bind to as a parameter to the constructor of your dialog window. The constructor then assigns it to an internal property to which your XAML code can bind to.


Try this method, easy and clean.

<!-- In user countrol resources -->
    <UserControl.Resources>
        <CollectionViewSource Source="{Binding Currencies}" x:Key="Currencies"/>
    </UserControl.Resources>

<!-- below inside ex. DataGrid -->
  <ComboBox ItemsSource="{Binding Source={StaticResource Currencies}}" IsSynchronizedWithCurrentItem="False"
            DisplayMemberPath="IsoCode"
            SelectedItem="{Binding BaseCurrency}"/>

<!-- IsSynchronizedWithCurrentItem="False" is important, otherwise ComboBoxes will select same item for each child viewmodel -->

reference to blogpost http://kostylizm.blogspot.ru/2014/04/wpf-combobox-itemssource-bind-to-parent.html

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号