Wiki


Wiki Table of Contents

Page Details

Published by:
This page has not yet been rated

Silverlight Tip of the Day #60 – How to load a XAML Control From a File or String

Nếu bạn có một control được viết bằng XAML mà được chứa trong dự án của bạn, bạn có thể nạp và tạo nó một cách trực tiếp từ tập tin bằng cách sử dụng phương thức: System.Windows.Markup.XamlReader.Load().Phương thức này cũng có thể được sử dụng để tạo trực tiếp một Silverlight control từ một string.

Để minh họa điều này, tôi đã tạo hai hàm được gọi là LoadFromXAML(). Hàm thứ nhất  có một tham số có kiểu là  URI để  trỏ đến tập tin XAML trong  project mà bạn muốn load. Hàm thứ hai có một tham số kiểu string đại diện cho control.

public static object LoadFromXaml(Uri uri)
{
    System.Windows.Resources.StreamResourceInfo streamInfo = System.Windows.Application.GetResourceStream(uri);
 
    if ((streamInfo != null) && (streamInfo.Stream != null))
    {
        using (System.IO.StreamReader reader = new System.IO.StreamReader(streamInfo.Stream))
        {
            return System.Windows.Markup.XamlReader.Load(reader.ReadToEnd());
        }
    }
 
    return null;
}
public static object LoadFromXamlString(string xamlControl)
{
    return System.Windows.Markup.XamlReader.Load(xamlControl);
}

Những phương thức trên trả về một đối tượng chung mà có thể được ép kiểu thành đối tượng mà bạn đang load. Thí dụ:

Button myButton = (Button)LoadFromXaml(new Uri("/LoadXaml;component/MyButton.xaml", UriKind.Relative));

hay

string buttonXAML = "<Button xmlns='http://schemas.microsoft.com/client/2007' Width=\"100\" Height=\"100\" Content=\"Click Me\"></Button>";

Button myButton = (Button) LoadFromXaml(buttonXAML);

Lưu ý rằng trong XAML bạn phải khai báo một XML namespace mặc định như dòng được bôi màu vàng dưới đây:

<Button xmlns='http://schemas.microsoft.com/client/2007' Width="100" Height="100" Content="Click Me"></Button>

Nếu bạn không khai báo namespace này , bạn sẽ nhận được error sau:

AG_E_PARSER_MISSING_DEFAULT_NAMESPACE [Line: 0 Position: 0]

 

Thank you,
--Mike Snow

Recent Comments

Leave the first comment for this page.