何をしようとしているのかを示すために、いくつかのコードを提供する必要があります。アイテムが既に選択されている場合、RichEdit
コントロールのテンプレートがまだ設定されていないのはなぜですか?
WPF を扱うときは、ビュー モデルへのバインディングに慣れることが役立ちItemsSource
ますSelectedItem
。あなたが説明したシナリオを考えると、必要に応じて値コンバーターを使用してSelectedItem
、ビューモデルへのバインディングを使用し、コントロールのテンプレートを同じビューモデルプロパティにバインドします。RichEdit
このようにして、クリックイベントなどをいじる必要はありません。ビュー モデルのプロパティがDependencyProperty
またはPropertyChanged
イベントを発生させる場合 (「 」を参照INotifyPropertyChanged
)、RichEdit
コントロールのテンプレートはドロップダウンでの選択を自動的に反映する必要があります。
**編集**あなたのコメントに基づいて、コンボの選択に基づいてテキストを設定するが、ユーザーがそのテキストをカスタマイズできるようにすることが必要な動作であると想定しています。ただし、編集した場合は、コンボ値を再選択してテキストをリセットできる必要があります。問題は、アイテムが既に選択されている場合、フックするイベントが発生しないことです。解決策は、テキストの内容が変更された場合、コンボの選択を解除することです (コンボがテキスト ボックスの内容を反映しなくなるため)。バインディングはこれを非常にうまく管理できます。
このサンプル ビューでは、わかりやすくするために TextBox を使用しています。
<Window x:Class="UISample.UITemplateSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="UITemplateSample" Height="300" Width="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<ComboBox ItemsSource="{Binding Path=Templates}" SelectedItem="{Binding Path=SelectedTemplate}" DisplayMemberPath="Name"/>
<TextBox Grid.Row="1" AcceptsReturn="True" TextWrapping="Wrap" Text="{Binding Path=Text}"/>
</Grid>
ビューモデル:
class TemplateSampleViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<TextTemplate> Templates
{
get;
private set;
}
private TextTemplate _selectedTemplate;
public TextTemplate SelectedTemplate
{
get{ return _selectedTemplate; }
set
{
if ( _selectedTemplate == value )
return;
_selectedTemplate = value;
if (_selectedTemplate != null)
Text = _selectedTemplate.TemplateText;
firePropertyChanged("SelectedTemplate");
}
}
private string _text;
public string Text
{
get { return _text; }
set
{
if ( _text == value )
return;
_text = value;
firePropertyChanged( "Text" );
var matchingTemplate = Templates.FirstOrDefault( t => t.TemplateText == _text );
SelectedTemplate = matchingTemplate;
}
}
public TemplateSampleViewModel(IEnumerable<TextTemplate> templates)
{
Templates = new ObservableCollection<TextTemplate>(templates);
}
private void firePropertyChanged(string propertyName)
{
if ( PropertyChanged != null )
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
そしてそれを配線します:
var viewModel = new TemplateSampleViewModel(new[]
{
new TextTemplate {Name = "First", TemplateText = "This is the first item"},
new TextTemplate {Name = "Second", TemplateText = "This is the second item"},
new TextTemplate {Name = "Third", TemplateText = "This is the third item"},
});
var test = new UITemplateSample {DataContext = viewModel};
test.Show();
これによりコンボ ボックスがバインドされ、アイテムが選択されると、テキスト ボックスが自動的に更新されます。テキスト ボックスの内容が変更されると、テンプレートがまだ一致するかどうかが検査され、一致しない場合はコンボ アイテムが選択解除されます。エントリがテンプレートと一致する場合、そのテンプレートが自動的に選択されます。