Extended ComboBox在MouseWheel滚动上设置SelectedItem

时间:2014-03-30 13:59:01

标签: c# wpf combobox custom-controls

我有一个源自ComboBox的自定义控件。我已经覆盖了样式以添加一个按钮,该按钮在单击时将内容设置为NULL。控件在CustomControlLibrary中定义,模板在Themes \ Generic.xaml中设置。它正在工作,但问题是,当我使用鼠标滚轮滚动Combobox的项目时,SelectedItem-Binding正在更新,虽然我没有点击任何项目。当我使用普通的ComboBox时,它按预期工作。


我的自定义控件:

public class NullableComboBox : ComboBox
{
  private ICommand m_delCommand;

  static NullableComboBox()
  {
    DefaultStyleKeyProperty.OverrideMetadata(typeof(NullableComboBox), new FrameworkPropertyMetadata(typeof(NullableComboBox)));
  }

  public ICommand DelCommand
  {

    get { return m_delCommand ?? (m_delCommand = new RelayCommand(param => HandleDelCommand())); }

  }

  private void HandleDelCommand()
  {
    SelectedItem = null;
  }
}

资源字典中的样式:

<Style TargetType="{x:Type local:NullableComboBox}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type local:NullableComboBox}">
        <Grid>
          <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="Auto" />
          </Grid.ColumnDefinitions>

          <ComboBox Name="Cmb" Margin="0,0,-1,0"
                                ItemsSource="{Binding ItemsSource, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
                                DisplayMemberPath="{Binding DisplayMemberPath, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
                                SelectedValue="{Binding SelectedValue, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
                                SelectedItem="{Binding SelectedItem, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
                                SelectedValuePath="{Binding SelectedValuePath, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}" />

          <Button Grid.Column="1" Content=" X " Command="{Binding DelCommand, RelativeSource={RelativeSource TemplatedParent}}" MinWidth="0" MinHeight="0" >
            <Button.Style>
              <Style TargetType="Button">
                <Style.Setters>
                  <Setter Property="Background" Value="{Binding Background, ElementName=Cmb}" />
                  <Setter Property="Margin" Value="-1,0,0,0" />
                </Style.Setters>
              </Style>
            </Button.Style>
          </Button>
        </Grid>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

ViewModel中的相关项目(我在此处遗漏了属性更改通知):

public List<string> Items { get; set; }

private string selectedItem;
public string SelectedItem 
{
  get { return selectedItem; }
  set
  {
    selectedItem = value;
  }
}

在视图中使用控件:

<custom:NullableComboBox ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" />



如果SelectedItem没有在MouseWheel滚动上更新,我该怎么办?

0 个答案:

没有答案