好久沒有更新文章,今天抽空來分享一下最近玩耍的自定義控件;里面包含了自定義控件、依賴屬性和路由事件;來看看最終實現的效果:1、先來看看前臺Xaml布局和綁定:
<Style TargetType="{x:Type Cores:UploadWithProgressControl}"><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type Cores:UploadWithProgressControl}"><WrapPanel><Grid><TextBox Background="#323232"Style="{StaticResource TriggerTextBox}"IsReadOnly="True" Text="{TemplateBinding FilePath,Converter={StaticResource FilePathToFileNameConverter}}"VerticalContentAlignment="Center"/><Button x:Name="SelectFileButton" Style="{StaticResource OpenFileButton}"HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,15,5,15"/></Grid><Button Content="更新" x:Name="UpdateButton" Margin="10,10,0,10"Style="{StaticResource BaseButton}"IsEnabled="{TemplateBinding CurrentState,Converter={StaticResource UpdateStateEnumToButtonIsEnabledConverter}}"/></WrapPanel></ControlTemplate></Setter.Value></Setter>
</Style>
2、后臺代碼,關鍵點在TemplatePart和GetTemplateChild:
3、對于文件的選擇無非就是控件內部依賴屬性的處理:
private void SelectFileButton_Click(object sender, RoutedEventArgs e){System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog{Title = "選擇要升級的文件",Filter?=?"升級程序(*.bin)|*.bin|所有文件(*.*)|*.*"};System.Windows.Forms.DialogResult isSelected = openFileDialog.ShowDialog();if(isSelected == System.Windows.Forms.DialogResult.OK){//選擇的文件string fileName = openFileDialog.FileName;FilePath?=?fileName;CurrentState = UpdateStateEnum.SelectFile;OperateType = OperateTypeEnum.SelectFile;}}
4、對于更新按鈕就需要自定義路由事件了,畢竟是處理控件以外的邏輯了:
5、可以用Code Snippet快速創建路由事件:
https://andrewharcourt.com/articles/code-snippet-for-wpf-routed-event
6、最后來個調用完事:
<Cores:UploadWithProgressControl VerticalAlignment="Center" HorizontalAlignment="Center"IsUploading="{Binding FirstData.IsUpload,Mode=TwoWay}"ProgressValue="{Binding?FirstData.ProgressValue,Mode=TwoWay}"CurrentState="{Binding FirstData.UpdateState,Mode=TwoWay}"Update="UploadWithProgressControl_Click"/>
最終簡單的效果先這樣吧;以后有時間的話,可以再去摸索一下更復雜的效果
;編程不息、Bug不止、無Bug、無生活
;改bug的冷靜、編碼的激情、完成后的喜悅、挖坑的激動 、填坑的興奮;這也許就是屌絲程序員的樂趣吧;今天就到這里吧;希望自己有動力一步一步堅持下去;生命不息,代碼不止;大家抽空可以看看今天分享的效果,有好的意見和想法,可以在留言板隨意留言;我看到后會第一時間回復大家,多謝大家的一直默默的關注和支持!如果覺得不錯,那就伸出您的小手點個贊并關注一下!