日常问题总结Focus无法设置焦点MouseLeftDown鼠标左键按下查看ListBox中的SelectIndex在第一次为-1数据校验失败则焦点回到控件中成功则发送信息DataGrid设置边框颜色DataGrid设置Cell中文字居中在ItemsControl中添加Loaded事件发现有的控件并没有渲染完毕DataGrid设置选中行同时设置滚动条滚动到选中位置Canvas中绘制内容之后第一次位置不正确自定义ComboBox下拉样式导致下拉箭头点击没有反应CheckBox类似的Content做换行处理Focus无法设置焦点publicMainWindow(){InitializeComponent();this.LoadedMainWindow_Loaded;}privatevoidMainWindow_Loaded(objectsender,RoutedEventArgse){myButton.Focus();}解决方案添加Loaded方法在Loaded方法中设置焦点Loaded为画面渲染完成后执行MouseLeftDown鼠标左键按下查看ListBox中的SelectIndex在第一次为-1标题是一个问题描述在使用MVVMPrism8时 在ListBox添加了MouseLeftDown用来判断鼠标点击之后再点击同一个位置改变其状态的需求发现过程中SelectIndex第一次无论点击哪里都返回-1而且在改变选中index的时候获取的还是上一次选中的index原因因为SelectIndex和SelectItem都是在SelectionChanged中改变的而SelectionChanged是在MouseLeftDown后执行所以获取不到准确的SelectIndex和SelectItem数据校验失败则焦点回到控件中成功则发送信息在ViewModel中通过CommandParameter将TextBox对象传到ViewModel进行操作失败折中方案在View.xaml.cs中做数据验证在ViewModel做验证成功后处理TextBoxx:NametextBoxNameGrid.Column1LostKeyboardFocusTextBox_LostFocus// 这个成功后才会触发下面Command方法Text{Binding Value, ModeTwoWay, UpdateSourceTriggerPropertyChanged}dxmvvm:Interaction.Behaviorsdxmvvm:EventToCommandCommand{Binding PathDataContext.TextBoxLostCommand, RelativeSource{RelativeSource AncestorType{x:Type UserControl}}}CommandParameter{Binding ElementNametextBoxName}EventNameLostFocus//dxmvvm:Interaction.Behaviors/TextBoxDataGrid设置边框颜色StyleTargetTypeDataGridSetterPropertyHorizontalGridLinesBrushSetter.ValueSolidColorBrushColorWhite//Setter.Value/SetterSetterPropertyVerticalGridLinesBrushSetter.ValueSolidColorBrushColorWhite//Setter.Value/Setter/StyleDataGrid设置Cell中文字居中Stylex:KeyDataGridTextColumnCenterSytleTargetType{x:Type TextBlock}SetterPropertyHorizontalAlignmentValueCenter/SetterPropertyVerticalAlignmentValueCenter//Style...DataGridTextColumnHeader工站名称Width*Binding{Binding OCVName}ElementStyle{StaticResource DataGridTextColumnCenterSytle}在ItemsControl中添加Loaded事件发现有的控件并没有渲染完毕// 延迟加载防止UI未加载完成就开始处理Dispatcher.BeginInvoke(DispatcherPriority.Loaded,newAction((){// 处理内容}));DataGrid设置选中行同时设置滚动条滚动到选中位置this.dataGrid_Patches.SelectedItemitem;this.dataGrid_Patches.ScrollIntoView(item);Canvas中绘制内容之后第一次位置不正确Canvas_Box.UpdateLayout();在绘制内容之前先强制更新Canvas的大小布局原因就是第一次绘制还没有绘制出正确的宽高所以导致位置不正确自定义ComboBox下拉样式导致下拉箭头点击没有反应Pathx:NameArrowMargin0,0,5,0HorizontalAlignmentRightVerticalAlignmentCenterDataM 0,0 L 4,4 L 8,0 ZFill{TemplateBinding Foreground}RenderTransformOrigin1,0.5IsHitTestVisibleFalse// 注意这里选择让鼠标事件穿透Path否则无法触发下拉点击Path.RenderTransformScaleTransformScaleX3ScaleY3.5//Path.RenderTransform/PathCheckBox类似的Content做换行处理普通方式是Content修改为放置两个TextBlock,其实一个换行符(#x0a;)就可以搞定Content这是第一句#x0a;这是第二句博主用于记录工作中遇到的问题所以写的不是很详细有问题可以留言讨论