Je ne sais pas trop comment s'y prendre exactement. J'ai un ObservableCollection statique dans la classe NameField.cs. Je n'ai juste aucune idée de comment lier à la liste.WPF Custom Control - Comment lier une liste à partir d'un ObservableCollection statique?
- Est-ce que je ne devrais pas utiliser un ListBox?
- Devrais-je utiliser un DependencyProperty?
- Devrais-je exposer ObservableCollection à travers une propriété ou par le public?
Je ne sais pas quoi faire ...
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace MyWPF
{
[TemplatePart(Name = NameField.ElementPrefixBox, Type = typeof(ListBox))]
public class NameField : Control
{
private const String ElementPrefixBox = "PART_PrefixBox";
private static ObservableCollection<NamePrefix> _namePrefixes;
static NameField()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(NameField), new FrameworkPropertyMetadata(typeof(NameField)));
_namePrefixes = new ObservableCollection<NamePrefix>();
}
public static void AddNamePrefix(NamePrefix namePrefix)
{
lock (_namePrefixes)
{
_namePrefixes.Add(namePrefix);
}
}
public static IEnumerator<NamePrefix> GetNamePrefixes()
{
return _namePrefixes.GetEnumerator();
}
}
/// <summary>
/// A Key/Value structure containing a Name Prefix ID and String value.
/// </summary>
public struct NamePrefix
{
public NamePrefix(Int32 id, String prefix)
: this()
{
ID = id;
Prefix = prefix;
}
public Int32 ID { get; set; }
public String Prefix { get; set; }
}
}
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyWPF"
xmlns:con="clr-namespace:MyWPF.Converters"
>
<Style TargetType="{x:Type local:NameField}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:NameField}">
<StackPanel Orientation="Horizontal">
<TextBlock TextWrapping="NoWrap" Text="Name:" VerticalAlignment="Center" Margin="3" />
<ListBox x:Name="PART_PrefixBox" VerticalAlignment="Center" Margin="3" >
<ListBox.ItemBindingGroup>
<BindingGroup Name="NamePrefixes"/>
</ListBox.ItemBindingGroup>
</ListBox>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>