"シンプルな"ケースで作業しています。私はDependencyPropertyを実装する新しいカスタムコントロールを作成するのが好きです。次のステップでは、両方向のプロパティを更新するためのバインディングを作成したいと思います。私はこのケースのための簡単なサンプルを構築しましたが、バインディングは動作していないようです。私はFrameworkPropertyMetadataを使用してDPControlのプロパティを更新する方法を見つけましたが、OnPropertyChangedイベントを使用することも良い考えであるかどうかはわかりません。 HEREバインディングの依存関係プロパティを作成する方法
は私のサンプルプロジェクトです:
私のコントロールは、単にラベル
<UserControl x:Class="WPF_MVVM_ListBoxMultiSelection.DPControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WPF_MVVM_ListBoxMultiSelection"
mc:Ignorable="d" Height="84.062" Width="159.641">
<Grid Margin="0,0,229,268">
<Label Content="TEST" x:Name="label" Margin="0,0,-221,-102"/>
</Grid>
</UserControl>
とカスタム依存関係プロパティを実装が含まれています。現時点では、FramePropertyMetadataのPropertyChangedメソッドも実装しており、このメソッドではラベルのコンテンツを設定していますが、両方向で動作させるのが好きです。
public partial class DPControl : UserControl
{
public DPControl()
{
InitializeComponent();
}
public string MyCustomLabelContent
{
get { return (string)GetValue(MyCustomLabelContentProperty);}
set
{
SetValue(MyCustomLabelContentProperty, value);
}
}
private static void OnMyCustomLabelContentPropertyChanged(DependencyObject source,
DependencyPropertyChangedEventArgs e)
{
DPControl control = (DPControl)source;
control.label.Content = e.NewValue;
}
public static readonly DependencyProperty MyCustomLabelContentProperty = DependencyProperty.Register(
"MyCustomLabelContent",
typeof(string),
typeof(DPControl),
new FrameworkPropertyMetadata(null,
OnMyCustomLabelContentPropertyChanged
)
);
Iは、ウィンドウ内単にこのコントロールを使用する:
<local:DPControl MyCustomLabelContent="{Binding MyLabelContent, Mode=TwoWay}" Margin="72,201,286,34"/>
MyLabelContent
もINotifyPropertyChangedインターフェイスを実装しているビューモデルにおける特性です。
public class ViewModel_MainWindow:NotifyPropertyChanged
{
private string _myLabelContent;
public string MyLabelContent
{
get { return _myLabelContent; }
set { _myLabelContent = value;
RaisePropertyChanged();
}
}...
どのように私はそれを働かせることができます:カスタムプロパティの新しいコントロールでバインディング機能を使用します。ユーザーコントロールで
ありがとう、これは単純なケースでは機能しますが、ItemsSelectedを取得するためのリストボックスのwrapper-usercontrolのように実装したいのですが、動作しません。この場合のヒント? – Kinimod
@Kinimod ItemsSelectedは痛みです:あなたはそれを縛ることはできません。またコレクションなので、変更通知を処理する必要があります。それは別の質問です。 –
あなたはそれが痛みです。バインディングのSelectedItemsリストを持つリストボックスのような、リストを扱う他のサードパーティコントロールに対する提案はありますか? – Kinimod