I have the following sample from MSDN:
<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowD开发者_Go百科efinitions>
<RowDefinition Height="25" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<riaControls:DomainDataSource Name="source" QueryName="GetProductsByColor" AutoLoad="true">
<riaControls:DomainDataSource.DomainContext>
<domain:ProductDomainContext />
</riaControls:DomainDataSource.DomainContext>
<riaControls:DomainDataSource.QueryParameters>
<riaControls:Parameter ParameterName="color" Value="{Binding ElementName=colorCombo, Path=SelectedItem.Content}" />
</riaControls:DomainDataSource.QueryParameters>
</riaControls:DomainDataSource>
<ComboBox Width="60" Grid.Row="0" x:Name="colorCombo">
<ComboBoxItem Content="Black" />
<ComboBoxItem Content="Blue" />
</ComboBox>
<data:DataGrid Grid.Row="1" ItemsSource="{Binding Data, ElementName=source}" />
</Grid>
Well, as you can see the line that creates a parameter binding is set:
<riaControls:Parameter ParameterName="color" Value="{Binding ElementName=colorCombo, Path=SelectedItem.Content}" />
However if I am to try this with code it doesn't work:
Binding binding = new Binding();
binding.ElementName = "colorCombo";
//binding.Source = this.colorCombo; also doesn't work!
binding.Path = new PropertyPath("SelectedItem.Content");
binding.Mode = BindingMode.OneWay;
Parameter param = new Parameter();
param.Value = binding;
source.QueryParameters.Clear();
source.QueryParameters.Add(param);
Any ideas on what I am doing wrong?
To bind programmatically, you have to use BindingOperations.SetBinding
. Currently you're just setting the Value
property to a Binding
instance rather than binding it.
BindingOperations.SetBinding(param, Parameter.ValueProperty, binding)
Plus, change back your binding to Source = this.colorCombo
. Element names are usually resolved within a XAML context, which is no present in code behind.
精彩评论