【发布时间】:2019-02-22 00:15:40
【问题描述】:
我需要在控件展开之前加载 ComboBox ItemsSource。如果加载失败,我想将边框画笔颜色设置为红色并显示错误提示。我可以在ICommand.Execute 方法中执行此操作,还是应该使用ValidationRule 之类的方法?
代码:
class ViewModel : INotifyPropertyChanged
{
public string Server { get {...} set {...} }
public ObservableCollection<string> ServerCollection { get; }
public ICommand LoadServerListCommand { get; }
protected ConnectionViewModel()
{
ServerCollection = new ObservableCollection<string>();
LoadServerListCommand = new DelegateCommand( LoadServerList );
}
private void LoadServerList( object param )
{
var comboBox = param as ComboBox;
if ( comboBox != null && !comboBox.IsDropDownOpen )
{
try
{
ServerCollection.Clear();
///... Load();
comboBox.BorderBrush = //default;
comboBox.ToolTip = null;
}
catch( InvalidOperationException ex )
{
comboBox.BorderBrush = //red;
comboBox.ToolTip = new ToolTip()
{
Content = ex.Message
};
}
}
}
}
XAML:
<ComboBox x:Name="cbServer" ItemsSource="{Binding ServerCollection}"
SelectedItem="{Binding Server, Mode=TwoWay}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="PreviewMouseDown">
<i:InvokeCommandAction Command="{Binding Path=LoadServerListCommand}"
CommandParameter="{Binding ElementName=cbServer}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>
【问题讨论】:
-
你不应该从你的 ViewModel 修改你的视图,视图应该改变自己!深入了解我认为可以帮助您的 DataBinding