gpt4 book ai didi

c# - 如何使用MVVM以编程方式更改ComboBox SelectedValue

转载 作者:行者123 更新时间:2023-12-03 11:03:40 28 4
gpt4 key购买 nike

我有一个带有项目A,B,C,D,E的ComboBox。

用户选择后如何更改组合框的SelectedValue,因此,如果用户从列表项“A”中选择,则SelectedValue将为“D”(就像他自己选择了D)。

Xml:

<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" Height="25" Width="100" />
<ComboBox
IsDropDownOpen="{Binding IsDropDownOpen, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
ItemsSource="{Binding OffsetValues}"
SelectedValue="{Binding NodeCategory, Mode=TwoWay}"

Height="25" Width="100" IsHitTestVisible="False" Background="AliceBlue">
<ComboBox.Resources>
<sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">0</sys:Double>
</ComboBox.Resources>
</ComboBox>
</StackPanel>

ViewModel:
class ViewModel : ViewModelBase
{

private IList<string> offsetValues = new List<string>() { "mV", "V" };
public IList<string> OffsetValues
{
get
{
return offsetValues;
}
set
{
offsetValues = value;
}
}


private bool isDropDownOpen;

public bool IsDropDownOpen
{
get { return isDropDownOpen; }
set
{
isDropDownOpen = value;
OnPropertyChanged();
}
}

private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged( "Name" );

if( _name != "" )
{
isDropDownOpen = true;
OnPropertyChanged( "IsDropDownOpen" );
}

}
}

private string _NodeCategory;
public string NodeCategory
{
get
{
return _NodeCategory;
}
set
{
if( Convert.ToDouble( _name ) > 1000 )
{
_name = "1.0";

OnPropertyChanged( "Name" );

_NodeCategory = OffsetValues[1];

OnPropertyChanged( "NodeCategory" );

}
else
{
_NodeCategory = value;
OnPropertyChanged( "NodeCategory" );
}
}
}
}


public class ViewModelBase : INotifyPropertyChanged
{

protected virtual void OnPropertyChanged( [CallerMemberName]string propertyName = null )
{
PropertyChanged.Invoke( this, new PropertyChangedEventArgs( propertyName ) );
}

public event PropertyChangedEventHandler PropertyChanged;

}

谢谢

最佳答案

添加xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
比当SelectedItemChanged之类的时候可以调用Command

    <ComboBox x:Name="NodeCategoriesCombobox">

<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding UpdateNodeCategoryCommand}" CommandParameter="{Binding ElementName=NodeCategoriesCombobox, Path=SelectedValue}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>

比您添加UpdateNodeCategoryCommand并更新NodeCategory属性
private RelayCommand<string> _updateNodeCategoryCommand ;
public RelayCommand<string> UpdateNodeCategoryCommand {
get { return _updateNodeCategoryCommand ?? (_updateNodeCategoryCommand = new RelayCommand<string>( nodeCategory => { NodeCategory=nodeCategory }));
}
}

关于c# - 如何使用MVVM以编程方式更改ComboBox SelectedValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40571478/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com