發表文章

目前顯示的是 6月, 2013的文章

WPF – Getting Started with MVVM

I've been working with MVVM and WPF for a couple of weeks now. I decided to log what I've learned here. Here goes a getting started tutorial with MVVM. Download the source code . The Model-View-ViewModel pattern was introduced by John Gossman to effectively utilize the functionality of WPF. Since then, MVVM has been used in a number of WPF applications with very impressive results. MVVM has three components: Model: It is your data or classes that represent entities in your application. It normally contains no WPF-specific code. View: This is the User Interface element visible to the user. Its DataContext is its ViewModel. ViewModel: It contains all the data that needs to be displayed and procedures to modify the model at will. The magic about MVVM is that the ViewModel knows nothing about the View. You see that this is very loosely coupled. The View knows the ViewModel but the ViewModel does not know the View. You can very easily replace the View without affecting t...

WPF - 深入 Style

圖片
Style 用來在類型的不同實例之間共享屬性、資源和事件處理程序,您可以將 Style 看作是將一組屬性值應用到多個元素的捷徑。   這是MSDN上對Style的描述,翻譯的還算中規中矩。Style(樣式),簡單來說,就是一種對屬性值的批處理,類似于Html的CSS,可以快速的設置一系列屬性值到UI元素。   示例   一個最簡單的Style的例子: <Window> <Grid> <Grid.Resources> <Style TargetType="{x:Type Button}" x:Key="ButtonStyle"> <Setter Property="Height" Value="22"/> <Setter Property="Width" Value="60"/> </Style> </Grid.Resources> <Button Content="Button" Style="{StaticResource ButtonStyle}"/> <Button Content="Button" Style="{StaticResource ButtonStyle}" Margin="156,144,286,145" /> </Grid> </Window>   關于Resources的知識,請參見 MSDN ,這里創建了一個目標類型為Button的ButtonStyle,兩個Button使用靜態資源( StaticResource )的查找方式來找到這個Style。Style中定義了Button的高度(Height)和寬度(Width),當使用了這個Style后,兩個Button無需手動設置,即可自動設置...

WPF – 使用 DrawingVisual 描繪圖形

圖片
在 WPF 中有很多種方式來描繪圖形, 其 DrawingVisual 是一個輕量級的 Class, 它需一個 container 來承接, 並不提供 Layout, Hit-Testing 及 Event-Handling. 那來實作一下如何使用 DrawingVisual 來描繪圖形. 建立一個 class, 它繼承 FrameworkElement Class, 並描繪一個 Rectangle . public class MyVisualHost : FrameworkElement { private VisualCollection childern; public MyVisualHost() { childern = new VisualCollection(this); childern.Add(CreateDrawingVisualRectangle()); } protected override int VisualChildrenCount { get { return childern.Count; } } protected override Visual GetVisualChild(int index) { return childern[index]; } private DrawingVisual CreateDrawingVisualRectangle() { DrawingVisual drawing = new DrawingVisual(); using (DrawingContext content = drawing.RenderOpen()) { content.DrawRectangle(Brushes.Red, new Pen(Brushes....