ElementName绑定失败

时间:2012-02-03 01:34:43

标签: wpf xaml data-binding

我有以下XAML:

<Grid>
    <Grid.RowDefinitions>
        ...
    </Grid.RowDefinitions>
    <DataGrid Grid.Row="0" ...>
        <DataGrid.Columns>
            ...
        </DataGrid.Columns>
    </DataGrid>

    <DockPanel Grid.Row="2">
        <CheckBox x:Name="DisplayMarkers" DockPanel.Dock="Top" Content="Display Data Points?"
                Margin="8,5,0,5" d:LayoutOverrides="Height" HorizontalAlignment="Left" IsChecked="False" />
        <vf:Chart DockPanel.Dock="Top" ScrollingEnabled="False" ZoomingEnabled="True" ToolBarEnabled="True">
            <vf:DataSeries AxisYType="Secondary" RenderAs="Line" DataSource="{Binding CdTeRoughnessList}"
                    XValueType="DateTime"
                    MarkerEnabled="{Binding ElementName=DisplayMarkers, Path=IsChecked}" Color="Navy"
                    LegendText="Roughness Std. Dev.">

此绑定失败:MarkerEnabled="{Binding ElementName=DisplayMarkers, Path=IsChecked}"

我正在尝试绑定到我的Checkbox上名为'DisplayMarkers'的IsChecked属性。当我运行它时,在VS 2010的调试模式下,输出窗口显示绑定失败。它找不到名为的元素'复选框'。谁能告诉我为什么?

我从VS得到的错误是:

System.Windows.Data Error: 4 : Cannot find source for binding with reference 

    'ElementName=DisplayMarkers'. BindingExpression:Path=IsChecked; DataItem=null; target element is 'DataSeries' (Name=''); target property is 'MarkerEnabled' (type 'Nullable`1')

3 个答案:

答案 0 :(得分:88)

您可能没有尝试绑定的名称范围,您可以尝试将ElementName构造替换为Source={x:Reference DisplayMarkers}

有关潜在的周期性依赖性错误的解决方法,请参阅:https://stackoverflow.com/a/6858917/546730

答案 1 :(得分:4)

我猜测Chart的编写器,当从FrameworkElement或其他任何东西派生时,没有意识到他们需要手动或通过覆盖将任何子元素添加到逻辑树中。在推导时你不能免费获得它。

打破逻辑树会破坏子元素通过ElementName绑定的能力。

If you are the author of the Chart object, you can see this related question and answer.

答案 2 :(得分:0)

对于其他读者,另一个可能的原因是,上面的vf:Chart的作用是使用UserControl而不是custom control。我编写了一个拆分按钮(以图表的角色),并将其从UserControl更改为自定义控件,从而使ElementName绑定起作用。

相关问题