28080

How can I set a binding to a Combox in a UserControl?

I have spent several days on this issue and can't seem to get it to work.

I have a user control that is saved out to a xaml file with the following code:

StringBuilder outstr = new StringBuilder(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.OmitXmlDeclaration = true; XamlDesignerSerializationManager dsm = new XamlDesignerSerializationManager(XmlWriter.Create(outstr, settings)); dsm.XamlWriterMode = XamlWriterMode.Expression; System.Windows.Markup.XamlWriter.Save(test1, dsm); String saveCard = outstr.ToString(); File.WriteAllText("inputEnum.xaml", saveCard);

Xaml for the user control:

<Grid > <Grid.ColumnDefinitions> <ColumnDefinition Width="{Binding DescriptionWidth}" /> <ColumnDefinition Width="{Binding ValueWidth}" /> </Grid.ColumnDefinitions> <ComboBox Grid.Column="1" Background="White" FontSize="{Binding FontSizeValue}" Width="Auto" Padding="10,0,5,0" ItemsSource="{Binding ComboItemsProperty}" SelectedIndex="{Binding EnumSelectedIndex}"> </ComboBox> </Grid>

The ItemsSource in the combobox is what is giving me problems. When I save an instance of this usercontrol out to a file, from my understanding, the {Binding ComboItemsProperty} is lost. So, in the constructor of my usercontrol I have:

public UserInputEnum() { InitializeComponent(); Binding bind = new Binding(); bind.Mode = BindingMode.TwoWay; bind.Source = this; bind.Path = new PropertyPath("ComboItemsProperty"); this.SetBinding(ComboBox.ItemsSourceProperty, bind); }

Here is my property and the changed method:

EnumItemsCollection ComboItems = new EnumItemsCollection(); public EnumItemsCollection ComboItemsProperty { get { return ComboItems; } set { ComboItems = value; OnPropertyChanged("ComboItemsProperty"); } } public void OnPropertyChanged(string propertyName) { getEnumItems(this.ComboItemsProperty, this.EnumSelectedIndex, this.ID, this.SubmodeID); PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this.ComboItems, new PropertyChangedEventArgs(propertyName)); } }

Just a note. EnumItemsCollection is a simple class that inherits off ObservableCollection. There is nothing else to this class. (not sure if this makes a difference).

I think this should work but when when I load the XAML file through the XAMLReader, my combobox items won't update.

EDIT:

I ran a little test on an instance of user control that wasn't loaded from XAML but is in the MainWindow.xaml.

Everything works fine. When I add to the ComboItemsProperty, the combobox updates.

So, I took away the {Binding ComboItemsProperty} and tried to set the binding in the code as above changing 'this' to the instance of the user control. Didn't work. This tells me it is the binding code that is not functioning correctly.

I'm fairly certain is the bind.Source line that is the issue. When it is in a UserControl I am unsure of what to put there.

EDIT:

Code that loads usercontrol from file:

FileStream stream = File.Open("usercontrol.xaml", FileMode.Open, FileAccess.Read); ComboBox cmb = System.Windows.Markup.XamlReader.Load(stream) as ComboBox;

It loads perfectly fine. The Binding just isn't working(ItemsSource={Binding ComboItemsProperty}) because Bindings aren't saved out.

I load it from a file because this program will have many User Interfaces in a sense. Each one will be loaded by a different person using the program.

Answer1:

You need to the set context of the instance containing your property <strong>ComboItemsProperty</strong>. So instead of 'this' u should set it to this.DataContext or other class object instance containing the ItemSource property you have defined..

Try this,

Binding bind = new Binding(); bind.Mode = BindingMode.TwoWay; bind.Source = this.DataContext; bind.Path = new PropertyPath("ComboItemsProperty"); this.SetBinding(ComboBox.ItemsSourceProperty, bind);

Update

According to Serialization Limitations of XamlWriter.Save available on msdn,

    <li>Many design-time properties of the original XAML file may already be optimized or lost by the time that the XAML is loaded as in-memory objects, and are not preserved when you call Save to serialize.</li> <li>Common references to objects made by various markup extension formats, such as StaticResource or Binding, will be dereferenced by the serialization process.</li> </ul>

    <strong>Conclusion</strong>, that I made out now is you cannot directly load the UserControl as whole by Serialization - Deserialization procedure of XAML. I think you can load the object instances by Serialization - Deserialization procedure on the DataContext of the UserControl i.e. the custom list(s) or object(s) you have databound.

Recommend

  • How can I extract columns from a fixed-width format in Perl?
  • Create a unique primary key (hash) from database columns
  • Scope(failure) in C++11?
  • Relationship between LR(0), LL(0), LALR(1), etc?
  • Git: failed to read object … Invalid argument
  • Add a TCombobox Column to a Firemonkey TGrid
  • JAXB Root Class Rename using binding.xml
  • Enterprise Architect Synchronize with Code
  • Set comboBox to custom display format
  • Codename one separate class along with statemachine class
  • Android Oreo JobIntentService Keep running in background for Android 7 &below and crashing often
  • twisted.internet.error.ConnectError when run scrapy spider
  • How to change default stop edit behavior in jtable
  • Run EF6 Query in separate Thread on WinForm Button Click Event
  • Is mp4 stream able with ffserver?
  • Specify HTTPS for custom WCF Binding
  • How to configure Cygnus in relation to Orion and Cosmos
  • How do you remove the JComboBox 'click and see dropdown' functionality?
  • Find longest path less than or equal to given value of an acyclic, directed graph in Python
  • R sqldf renaming a field in a select statement
  • Making Google Visualization - Annotation Chart to work in GWT
  • Available space left on drive - WinAPI - Windows CE
  • Updating product post meta data in admin meta box field
  • Cannot save model when using ember render helper
  • C#: Import/Export Settings into/from a File
  • SAXReader not re-ecape characters
  • Django model inheritance, filtering models
  • Spring boot 2.0.0.M4 required a bean named 'entityManagerFactory' that could not be found
  • Does it make sense to call System.gc() and Thread.sleep() when working on Bitmaps?
  • Create DicomImage from scratch using Dcmtk
  • AJAX Html Editor Extender upload image appearing blank
  • Highlight one bar in a series in highcharts?
  • Problems to linebreak with an int in JLabel
  • In LanguageTool, how do you create a dictionary and use it for spell checking?
  • Calling of Constructors in a Java
  • PHP: When would you need the self:: keyword?
  • Angular 2 constructor injection vs direct access
  • unknown Exception android
  • failed to connect to specific WiFi in android programmatically
  • How can I use threading to 'tick' a timer to be accessed by other threads?