How to include common XAML code in page? - cont.

jennyliu835 221 Reputation points
2020-08-23T00:45:02.07+00:00

Hi Peter,

I follow your example to load XAML using Visual Studio 2017 (.net 4.6.1). The project is built without any problem, but the text "This is text for Page 1" does not showed up. Please tell me what is wrong with the following steps and if there is any step I missed. Thanks.

1, I copied and pasted all your code to my Page1.xaml and Page1.xaml.cs. Please check out the attachments.
2, I added an new item "XamlWithControls.xaml" under "pages" folder and tried both "Page" and "Resource" for "Build Action" of this XAML.

Thanks again.

Jenny

19637-mainwindowxaml.txt19689-mainwindowxamlcs.txt19690-page1xaml.txt19706-page1xamlcs.txt19596-xamlwithcontrolsxaml.txt19597-file-structure.png

Developer technologies | Windows Presentation Foundation
0 comments No comments
{count} votes

Accepted answer
  1. DaisyTian-1203 11,646 Reputation points
    2020-08-24T02:34:50.183+00:00

    From your code, you need to do three things to read the XamlWithControls.xaml.

    1. Add the subfolder before XamlWithCotrols.xaml. get => (ContentControl)XamlReader.Load(new FileStream("pages/XamlWithControls.xaml", FileMode.Open));

    2.Make the XamlWithControls.xaml as Content for the Build Action
    3.[You missed this step]Choose Copy if newer/Copy always for Copy to Output Directiory.Reason: FileStream reads files in the bin\Debug folder under the current project when it using the relative path.
    19792-capture.png

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Peter Fleischer (former MVP) 19,341 Reputation points
    2020-08-23T05:44:42.667+00:00

    Hi Jenny,
    if you put your XamlWithControls in subfolder you must read from subfolder:

    public ContentControl LoadedXaml
      { get => (ContentControl)XamlReader.Load(new FileStream("pages/XamlWithControls.xaml", FileMode.Open)); }
    

    You can download my demo here.

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.