2013-10-10 49 views
0

我想在運行時將純XAML代碼添加到我的xaml元素中。有誰知道這是怎麼做到的嗎?謝謝。 我願做這樣的事情:myGrid.innerXAML = stringXAMLcode 這將導致以<grid name="myGrid">newgeneratedcodehere</grid>如何通過WPF中的c#代碼隱藏來編寫逐字XAML代碼?

在PHP中,你可以打印逐字HTML代碼直接插入HTML文件。這可能與C#? 如果沒有,任何人都可以提出解決辦法嗎? 謝謝!

+0

這似乎是一個非常糟糕的主意給我。您不使用過程代碼來定義或操作XAML中的UI。這就是'DataTemplates'的用途。 –

回答

2

有辦法做你問這裏什麼,

Creating WPF Data Templates in Code: The Right Way

:在這個CodeProject上的文章解釋不過,大多數情況下,你確實不需要日常操作。

如果你正在使用WPF,你真的需要從其他框架中拋棄傳統的方法,並擁抱The WPF Mentality。與WPF實現XAML相比,HTML(4,5或其他)看起來像是一個荒謬的笑話,因此在WPF中所有可能用於HTML的可怕黑客在WPF中完全不需要,因爲後者有很多內置的功能可幫助您以非常乾淨的方式實現高級UI功能。

WPF很大程度上基於DataBinding,並促進了界面和數據之間清晰明確的分離。

例如,這將是你會做什麼,當你想「顯示不同部分UI的」根據數據,通過使用WPF功能叫做DataTemplates到:

XAML:

<Window x:Class="MyWindow" 
      ... 
      xmlns:local="clr-namespace:MyNamespace"> 

     <Window.Resources> 

      <DataTemplate DataType="{x:Type local:Person}"> 

      <!-- this is the UI that will be used for Person --> 
      <TextBox Text="{Binding LastName}"/> 

      </DataTemplate> 

      <DataTemplate DataType="{x:Type local:Product}"> 

       <!-- this is the UI that will be used for Product --> 
       <Grid Background="Red"> 
        <TextBox Text="{Binding ProductName}"/> 
       </Grid> 

      </DataTemplate> 

     </Window.Resources> 

     <Grid> 
      <!-- the UI defined above will be placed here, inside the ContentPresenter --> 
      <ContentPresenter Content="{Binding Data}"/> 
     </Grid> 

    </Window> 

代碼背後:

public class MyWindow 
{ 
    public MyWindow() 
    { 
     InitializeComponent(); 
     DataContext = new MyViewModel(); 
    } 
} 

視圖模型:

public class MyViewModel 
{ 
    public DataObjectBase Data {get;set;} //INotifyPropertyChanged is required 
} 

數據模型:

public class DataObjectBase 
{ 
    //.. Whatever members you want to have in the base class for entities. 
} 

public class Person: DataObjectBase 
{ 
    public string LastName {get;set;} 
} 

public class Product: DataObjectBase 
{ 
    public string ProductName {get;set;} 
} 

注意我是如何談論我的DataBusiness Objects而不是擔心任何黑客操縱UI。

還要注意如何定義XAML文件中的DataTemplates將由Visual Studio中被編譯給我編譯時檢查我的XAML的,而不是把它一起在一個string的程序代碼,這當然不有任何一致性檢查。

我強烈建議您閱讀Rachel's回答(上面鏈接)和相關的博客文章。

WPF岩石

0

爲什麼不添加你想要的元素?例如:

StackPanel p = new StackPanel(); 
Grid g = new Grid(); 

TextBlock bl = new TextBlock(); 
bl.Text = "This is a test"; 

g.addChildren(bl); 

p.addChildren(g); 

您可以對XAML中存在的所有元素執行此操作。

問候

+0

*真的*看起來不像XAML ......你沒有看過這個問題,或者你正在回答一個不同的問題嗎? – Sheridan

0

您可以使用XamlReader創建UIElement,你可以設置爲內容控制和佈局容器的孩子:

string myXamlString = "YOUR XAML THAT NEEDED TO BE INSERTED"; 
    XmlReader myXmlReader = XmlReader.Create(myXamlString); 
    UIElement myElement = (UIElement)XamlReader.Load(myXmlReader); 
    myGrid.Children.Add(myElement);