У меня есть некоторые проблемы с настраиваемым элементом управления, который мне нужно создать. Я пытаюсь объяснить вам мои потребности в первую очередьWPF Customcontrol, Templates, Inheritance и Dependencyproperties
Мне нужно иметь выпадающее поле, которое позволяет проверять несколько элементов во время (с флажком), но я хочу, чтобы он был достаточно умным, чтобы привязываться к определенному типу.
Я нашел несколько MultiSelectionComboBox, но ни один из них не отражает мою потребность. Btw моя главная проблема в том, что я хочу иметь общий класс как
public class BaseClass<T> : BaseClass
{
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register("ItemsSource", typeof(IEnumerable<T>), typeof(BaseClass<T>), new FrameworkPropertyMetadata(null,
new PropertyChangedCallback(BaseClass<T>.OnItemsSourceChanged)));
private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
int i = 0;
//MultiSelectComboBox control = (MultiSelectComboBox)d;
//control.DisplayInControl();
}
public IEnumerable<T> ItemsSource
{
get { return (IEnumerable<T>)GetValue(ItemsSourceProperty); }
set
{
SetValue(ItemsSourceProperty, value);
}
}
}
public class BaseClass : Control
{
}
и больше контекста конкретного элемента, например
public class MultiCurr : BaseClass<Currency>
{
static MultiCurr()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MultiCurr), new FrameworkPropertyMetadata(typeof(MultiCurr)));
}
}
В моей App.xaml я определил ресурс как
<ResourceDictionary>
<Style TargetType="local:MultiCurr">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:MultiCurr">
<ComboBox Width="120" Background="Red" Height="30" ItemsSource="{Binding ItemsSource}" DisplayMemberPath="Description" ></ComboBox>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
В моей MainWindow я создал объект как
<Grid>
<local:MultiCurr x:Name="test" ItemsSource="{Binding Currencies}"></local:MultiCurr>
</Grid>
и MainWindow.cs определяется как
общественный частичный класс MainWindow: Window, INotifyPropertyChanged { частные валюты IList;
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
this.Loaded += MainWindow_Loaded;
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
var lst = new List<Currency>();
for (int i = 0; i < 10; i++)
{
var curr = new Currency
{
ID = i,
Description = string.Format("Currency_{0}", i)
};
lst.Add(curr);
}
Currencies = lst;
}
public IList<Currency> Currencies
{
get
{
return this.currencies;
}
set
{
this.currencies = value;
NotifyPropertyChanged("Currencies");
}
}
public event PropertyChangedEventHandler PropertyChanged;
// This method is called by the Set accessor of each property.
// The CallerMemberName attribute that is applied to the optional propertyName
// parameter causes the property name of the caller to be substituted as an argument.
private void NotifyPropertyChanged(String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
И вот результат ...
Мне было интересно, что я делаю неправильно? возможно ли, чего я добиваюсь?
Благодаря
UPDATE # 1:
Я видел, что основной проблемой является DataContext обычая UserControl
<Application.Resources>
<ResourceDictionary>
<Style TargetType="local:MultiCurr">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:MultiCurr">
<ComboBox Width="120" Background="Red" Height="30" ItemsSource="{Binding **Currencies**}" DisplayMemberPath="{Binding **DisplayMemeberPath**}" ></ComboBox>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
</Application.Resources>
Если я ставлю ItemsSource в валюте (это это свойство MainWindow). Если я ставлю ItemsSource и DisplayMemberPath (которые определены в BaseClass нет .. как я могу установить контекст UserControl к себе?)
UPDATE # 2 Я добавил GoogleDrive ссылку на проект here если кто-то хочет попробовать Решение
Благодаря
В вашем шаблоне привязки шаблона используйте привязку шаблона. –
является 'currencies'' ObservableCollection'? И, кстати, у вас не должно быть сеттеров для ваших списков. – Default