0

どうすればいいですか?私は次のことを試しました:

Xaml の場合:

        <DataTemplate x:Key="LogDataTemplate" DataType="data:Type1">
             <TextBlock Text="Type1" />                
        </DataTemplate>

        <DataTemplate x:Key="LogDataTemplate" DataType="data:Type2">
            <TextBlock Text="Type2" />
        </DataTemplate>
    </ResourceDictionary>
</UserControl.Resources>

     <ListBox ItemsSource="{Binding source}"
              ItemTemplate="{StaticResource LogDataTemplate}" />    
 </UserControl>

ビューモデル(UserControlのDataContextとして設定されています):

member x.source = new ObservableCollection<Object>()

ただし、DataTemplate の重複に関するエラーがあります

4

2 に答える 2

4

パラメータを削除しx:Keyます。ここで必要なのは暗黙の DataTemplates です。

編集:これは本当に小さな実例です:

MainWindow.xaml.cs

using System.Collections.ObjectModel;
using System.Windows;

namespace StackOverflow
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;
            Rectangles = new ObservableCollection<object>() { new RedRectangle(), new BlueRectangle() };
        }
        public ObservableCollection<object> Rectangles { get; set; }
    }
    public class RedRectangle { }
    public class BlueRectangle { }
}

MainWindow.xaml

<Window x:Class="StackOverflow.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:StackOverflow"
        Width="500" Height="300">
    <Window.Resources>
        <DataTemplate DataType="{x:Type local:RedRectangle}">
            <Rectangle Width="16" Height="16" Fill="Red" />
        </DataTemplate>
        <DataTemplate DataType="{x:Type local:BlueRectangle}">
            <Rectangle Width="16" Height="16" Fill="Blue" />
        </DataTemplate>
    </Window.Resources>
    <ListBox ItemsSource="{Binding Rectangles}" />
</Window>
于 2012-11-08T12:37:58.480 に答える
1

@Sisyphe のメンションのような暗黙のデータ テンプレートがあります。

しかし、実際の問題は、両方のテンプレートに同じ名前を付けたことです。x:Keyは辞書キーであり、スコープ内で一意である必要があります。それがエラーの内容です。

そうは言っても、@ Sisypheが言及しているように、この場合は暗黙的なデータテンプレートを使用したほうがよいでしょう。

于 2012-11-08T12:47:49.797 に答える