0
我想在運行時加載一段特定的XAML代碼。 使用下面的代碼,我可以加載存在於txt文件中的xaml。在運行時加載XAML
private void btnLoadXAML_Click(object sender, RoutedEventArgs e)
{
try
{
string LoadedFileName = @"C:\test\sample.txt";
//Load the file
FileStream Fs = new FileStream(@LoadedFileName, FileMode.Open);
Grid grdToLoad = new Grid();
grdToLoad.Height = 210;
grdToLoad.Width = 400;
grdToLoad = System.Windows.Markup.XamlReader.Load(Fs) as Grid;
grdLoadXAML.Children.Add(grdToLoad);
Fs.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
上面的代碼實際上將創建一個新的網格控制和負載存在於文本文件中的XAML和創建控件按代碼。 考慮下面的代碼...
<Window x:Class="MyWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title=" "
Height="270"
Width="420"
Background="{x:Null}"
Foreground="#FFFFFFFF"
ShowInTaskbar="False"
WindowStartupLocation="CenterScreen"
ResizeMode="NoResize"
WindowStyle="None"
AllowsTransparency="True"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
以上是「窗口」標籤。我只需要運行時的一些屬性。對於例如:下面的代碼
WindowStyle="None" AllowsTransparency="True"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
我不希望上面的硬編碼在XAML但在運行時將其插入,我該怎麼辦呢?我嘗試了最初提到的方法,但是運行時錯誤。
是否要訪問包含動態網格的Window類? – 2015-03-31 18:04:34
這可能會有所幫助:http://stackoverflow.com/questions/6768261/what-is-the-easiest-way-to-share-resources-between-usercontrols-in-a-wpf-user-co?rq= 1(是的,你可以加載字典在運行時。我只是想給一個方法) – cdmnk 2015-03-31 19:29:12
嗨..我想只會有一個窗口標籤與x:Class屬性? – ShefZee 2015-04-01 13:27:11