2

カスタム DataGrid 列定義を UserControl に移動しようとしています。

MyComboBoxColumn.xaml

<dg:DataGridTemplateColumn 
    x:Class="WpfDecomposition.MyComboBoxColumn"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:dg="clr-namespace:Microsoft.Windows.Controls;assembly=WpfToolkit"
    x:Name="_this"
    >

    <dg:DataGridTemplateColumn.Header>
        <Button Content="{Binding MyHeader, ElementName=_this}" ></Button>
    </dg:DataGridTemplateColumn.Header>

</dg:DataGridTemplateColumn>

MyComboBoxColumn.cs

public partial class MyComboBoxColumn : DataGridTemplateColumn
{
    public MyComboBoxColumn()
    {
        InitializeComponent();
    }

    public static DependencyProperty MyHeaderProperty = 
        DependencyProperty.Register("MyHeader", typeof(string), typeof(MyComboBoxColumn), new PropertyMetadata("TEST"));
}

メイン ウィンドウの XAML:

<dg:DataGrid CanUserAddRows="True" AutoGenerateColumns="False">
    <dg:DataGrid.Columns>
        <my:MyComboBoxColumn />
    </dg:DataGrid.Columns>
</dg:DataGrid>

列のヘッダーに「TEST」というボタンが表示されるはずですが、代わりに空のボタンが表示されます。バインディングが壊れているようです。なにが問題ですか?

4

2 に答える 2

2

名前の要素が見つからないため、機能していません_this。Visual Studio でコードをデバッグすると、出力ウィンドウに次のエラーが表示されます。

System.Windows.Data エラー: 4: 参照 'ElementName=_this' を使用したバインディングのソースが見つかりません。BindingExpression:Path=MyHeader; DataItem=null; ターゲット要素は 'Button' (Name='TestButton'); ターゲット プロパティは「コンテンツ」(タイプ「オブジェクト」)

見つからない理由については、WPFバインディングがビジュアルツリーを使用してバインディングのソースを見つけるためだと思います。この場合、MyComboBoxColumnはビジュアル ツリーにないため、その名前の要素を見つけることができません。

私もRelativeSource要素を見つけるために使用しようとしましたが、それもうまくいきませんでした - おそらく同じ理由で。

私が作業できる唯一のことはDataContext、コンストラクターでボタンのを列自体に設定することです。

public MyComboBoxColumn()
{
    InitializeComponent();

    this.TestButton.DataContext = this;
}

次に、XAML でバインドを変更します。

<tk:DataGridTemplateColumn.Header>
    <Button Content="{Binding Path=MyHeader}" x:Name="TestButton" />
</tk:DataGridTemplateColumn.Header>

これは最善の方法とは思えませんが、少なくとも機能します。

于 2009-04-01T11:39:54.957 に答える
0

コンストラクターでを設定したくない、または設定できないDataContext場合 (コードで列を動的に作成する場合など)、列のHeaderプロパティをバインド先のオブジェクト (データ コンテキスト) に設定してから、バインドすることができます。HeaderStyleデータ テンプレート内のこのオブジェクト。

詳細については、この質問を参照してください。

于 2010-10-13T08:34:32.547 に答える