我在Adorner中创建了一个名为OpacityAdorner的滑块控件,用于控制它所属控件的不透明度。我在http://www.codeproject.com/Articles/22952/WPF-Diagram-Designer-Part处遵循了Adorner示例,该示例使用xaml样式来帮助形成装饰,这可能会增加一些复杂性。 目前,我可以找到将滑块的ValueChange挂钩到ViewModel的唯一方法,看起来有点hacky,我更喜欢有绑定。我不能完全理解这一点:
protected override void OnInitialized( System.EventArgs e )
{
base.OnInitialized( e );
if( m_chrome != null && m_chrome.Template != null && m_slider == null )
{
m_chrome.ApplyTemplate();
m_slider = m_chrome.Template.FindName( "OpacitySlider", m_chrome ) as Slider;
if( m_slider != null )
{
m_slider.ValueChanged += opacity_value_changed;
//Binding opacityBinding = new Binding( "OpacityValue" );
//Control ctrl = (Control)m_chrome.DataContext;
//SettingsViewModel settingsVM = ctrl.DataContext as SettingsViewModel;
//opacityBinding.Source = settingsVM;
//////opacityBinding.Path = new PropertyPath( "OpacitySlider" );
//m_slider.SetBinding( SettingsViewModel.OpacticyProperty, opacityBinding );
}
m_opacity_button = m_chrome.Template.FindName( "OpacitySliderEnable", m_chrome ) as Ellipse;
if( m_opacity_button != null )
{
m_opacity_button.PreviewMouseLeftButtonDown += m_opacity_button_MouseLeftButtonDown;
}
}
}
和
void opacity_value_changed( object sender, RoutedPropertyChangedEventArgs<double> e )
{
Control ctrl = (Control)m_chrome.DataContext;
SettingsViewModel settingsVM = ctrl.DataContext as SettingsViewModel;
settingsVM.OpacityValue = e.NewValue;
}
理想情况下,我只是希望在已注释掉的部分中使用绑定,删除opacity_value_changed事件。我还想知道是否有更简洁的方法来检索SettingsViewModel,而不先获取容器chrome控件,然后从它的DataContext中获取视图模型?