[英]Binding problem in C# wpf
我在wpf中綁定綁定時遇到問題,我在其中可以執行一些輸入的文本框,然后嘗試將textinput綁定到自定義usercontrol。 這適用於RowDetailsTemplate中的usercontrol,但不適用於CellTemplate中的usercontrol。 對於CellTemplate中的每個對象,我得到以下錯誤輸出:
System.Windows.Data錯誤:4:找不到參考'ElementName = ScaleTextBox'的綁定源。 BindingExpression:Path = Text; DataItem = null; 目標元素是'Chart'(Name =''); 目標屬性是“ MaxValue”(類型“ Int32”)
我的代碼如下所示:
XAML
<ToolBarTray ToolBarTray.IsLocked="True" DockPanel.Dock="Top" Height="25">
<ToolBar Name="ButtonBar" >
<TextBox Height="23" Name="ScaleTextBox" Width="120" Text="400"/>
</ToolBar>
</ToolBarTray>
<DataGrid ItemsSource="{Binding Path=Items}" AutoGenerateColumns="False" IsReadOnly="True" RowHeight="25" RowDetailsVisibilityMode="VisibleWhenSelected">
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical" >
<my:UserControl ItemsSource="{Binding Path=Samples}" MaxValue="{Binding ElementName=ScaleTextBox, Path=Text}"/>-->
</StackPanel>
</DataTemplate>
</DataGrid.RowDetailsTemplate>
<DataGrid.Columns>
<DataGridTemplateColumn MinWidth="150" Header="Chart" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<my:UserControl ItemsSource="{Binding Path=Samples}" MaxValue="{Binding ElementName=ScaleTextBox, Path=Text}"/><!-- this is the problem -->
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
C#
public static readonly DependencyProperty MaxValueProperty = DependencyProperty.Register("MaxValue", typeof(int), typeof(Chart), new FrameworkPropertyMetadata(MaxValuePropertyChanged));
private static void MaxValuePropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
Console.WriteLine(e.NewValue);
}
我做錯了什么?
從這個連結
Columns集合只是Datagrid中的一個屬性。 此集合不在邏輯(或視覺)樹中,因此不會繼承DataContext,這導致沒有任何要綁定的對象。
因此,它適用於您的RowDetailsTemplate而不適用於您的列。
您可以嘗試以下方法:
<DataTemplate>
<my:UserControl
ItemsSource="{Binding Path=Samples}"
MaxValue="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:YourControlClassName}}, ElementName=ScaleTextBox, Path=Text}"/>
</DataTemplate>
好的,我使用ElementSpy解決了它,以查看elementSpy的工作原理,請看這里: http : //joshsmithonwpf.wordpress.com/2008/07/22/enable-elementname-bindings-with-elementspy/
和xaml:
<my:UserControl local:ElementSpy.NameScopeSource="{StaticResource ElementSpy}" ItemsSource="{Binding Path=Samples}" MaxValue="{Binding ElementName=ScaleTextBox, Path=Text}" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.