Silverlight 2 dynamic data binding Converter
-
12-09-2019 - |
Question
In Silverlight 2....
I have a RadioButton in my xaml code as follows:
<RadioButton GroupName="Gender" Content="Male" IsChecked="{Binding Path=Gender, ConverterParameter=1, Mode=TwoWay, Converter={StaticResource RadioStringConverter}}" Width="49" HorizontalAlignment="Left"/>
This works great. My issue is in trying to duplicate this functionallity dynamically.
RadioButton rb = new RadioButton() {GroupName = "Gender", Content = "Male" ,Width = (double)49,HorizontalAlignment = System.Windows.HorizontalAlignment.Left};
this works but when I try to put the converter in, it breaks. What is the proper way to do this? Any good working examples?
Here is what I tried....
RadioButton rb = new RadioButton() {GroupName = "Gender", Content = "Male" ,Width = (double)49,HorizontalAlignment = System.Windows.HorizontalAlignment.Left};
RadioStringConverter rsc = new RadioStringConverter();
Binding binding = new Binding(layout.FieldName) { Source = mainLayout.DataContext, Mode = BindingMode.TwoWay,ConverterParameter = 1,Converter = rsc}; // to emulate the "{StaticResource RadioStringConverter}"};
rb.SetBinding(RadioButton.IsCheckedProperty, binding);
sp.Children.Add(rb);
Although this compiles fine, it does not run correctly. 1) How do I reference the static resource dynamically? 2) How do I add this static resource to the XAML dynamically? Right now I have this reference hard coded.
Am I making this more difficult than it needs to be?
Solution
Solution found.... Basically I had to create an instance of the converter class and pass it's interface to the converter as such:
Binding binding = new Binding(layout.FieldName) { Source = mainLayout.DataContext, Mode = BindingMode.TwoWay,ConverterParameter = 1,Converter = (rsc as IValueConverter)};
Glad it turned out simple and doable :)
OTHER TIPS
Although it IS possible, as you have found out, are you sure you want to be creating the RadioButton dynamically?
I have been there... I have written the exact same code... but I soon realized that I was just doing it wrong. In my case, I used an ItemsControl, and bound the values using a template... completely eliminating the need to create them by myself dynamically.
I obviously don't know the larger context, but consider if you should be doing this more declaratively using some sort of dynamic container instead.
Actually, after I discovered MVVM, I completely eliminated the need for data converters at the UI layer. Data converters are obsolete with MVVM :)