0

次の XAML があります。

<ListView Name="_listView">
    <ListView.ItemTemplate>
        <DataTemplate>
            <Grid Name="_itemTemplate">
            </Grid>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

私が取得したいのは、バックグラウンド コードでプロパティを作成することです。これは、カスタム ユーザー コントロールを取得し、動的テンプレートとして配置します。このようなもの:

public UserControl ItemTemplate
{
    set { _itemTemplate.Content = value; }
}

したがって、コントロールをウィンドウの XAML に配置し、次のように項目テンプレートを宣言できます。

<local:MyCustomControl ItemTemplate="local:ControlThatActsAsItemTemplate"/>

そのような何かを達成する方法は?

4

2 に答える 2

1

Solution, that uses dependency property.

In custom UserControl declare dependency property that will inject item template to _listBox:

public static readonly DependencyProperty ItemTemplateProperty =
    DependencyProperty.Register("ItemTemplate",
                                typeof(DataTemplate),
                                typeof(AutoCompleteSearchBox),
                                new PropertyMetadata(ItemTemplate_Changed));

public DataTemplate ItemTemplate
{
    get { return (DataTemplate)GetValue(ItemTemplateProperty); }
    set { SetValue(ItemTemplateProperty, value); }
}

private static void ItemTemplate_Changed(
    DependencyObject d,
    DependencyPropertyChangedEventArgs e)
{
    var uc = (MyUserControl)d;
    uc._listBox.ItemTemplate = (DataTemplate)e.NewValue;
}

Now you are free to set a value to that property in hosting window XAML:

<Window.Resources>
    <Style TargetType="local:MyUserControl">
        <Setter Property="ItemTemplate">
            <Setter.Value>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding Path=PropertyName}"/>
                    </StackPanel>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

_listBox in your UserControl will gain a custom ItemTemplate that will respond to custom interface or class that you want to set as data source.

于 2013-07-30T12:06:03.350 に答える
1

これまでのところ、次の簡単な解決策を見つけました。

カスタム コントロール XAML で、ListBox を定義します。

<ListBox Name="_listBox"/>

コード ビハインドでプロパティを作成します。

public DataTemplate ItemTemplate
{
    get { return _listBox.ItemTemplate; }
    set { _listBox.ItemTemplate = value; }
}

XAML の親ウィンドウまたはコントロール セット リソース:

<Window.Resources>
    <DataTemplate x:Key="CustomTemplate">
        <TextBlock Text="{Binding Path=SomeProperty}"/>
    </DataTemplate>
</Window.Resources>

次に、カスタム コントロールを宣言します。

<local:CustomControl ItemTemplate="{StaticResource CustomTemplate}"/>

ここで、_listBox.ItemsSource に設定する必要があるインターフェイス インスタンスで構成される SomeProperty とデータ ソースを公開するインターフェイスが必要です。しかし、これは別の話です。

于 2013-07-29T09:56:00.117 に答える