how to use xaml magic - wpf

I have problems figuring out where to use what xaml keywords because its hard to figure out what hierarchy it wants. It seems there is some grand design on how and where to use attributes, properties or child nodes.
<Node Attribute="True">
<Node.Property />
</Node>
I found this beautiful page explaining all the ribbon menu properties, but have no idea how to use them in xaml. After half an hour of searching and trying everything I managed to get an Icon to show in the ribbon menu button.
What is the logic behind this all and how to figure out what to use where?
How to merge the ribbon menu with the application bar (the top bar on most windows applications)? So I get a nice Ribbon Application Menu, like in the example.
Is there a way to turn off xaml background compliation? I'd sacrifice Intellisense for this.
Because the xaml editor performance is abysmal, the are many suggestions for this, but none working so far.
Edit:
I know the xaml syntax, but there's no hint on what hierarchy to use. So if I find the object I want to use (because they are all available) it will only say I'm using the wrong object, it should ask for the kind of object it wants to be in.
Also in normal programming when you use a reference you can always use all classes in it. With xaml we must suddenly know what reference our class came from, also it won't find the reference for you, you either have to try all references to see if they have a certain class or find a code example.

Good questions. Its a little hard to get a feel for exactly what you're asking for in your #1 question, but I'll take a brief stab at that one. I do have an answer for your #2 question. I do not have an answer for your #3.
"1. What is the logic behind this all and how to figure out what to use where?"
Like Clemens mentioned, the XAML Overview does a pretty good job at explaining things.
I'm guessing that one of the main things that you're asking about is basically "when do you use attribute syntax vs property element syntax". From that doc:
For some properties of an object element, attribute syntax is not possible, because the object or information necessary to provide the property value cannot be adequately expressed within the quotation mark and string restrictions of attribute syntax. For these cases, a different syntax known as property element syntax can be used....
Now about this part of your question...
"Also in normal programming when you use a reference you can always use all classes in it. With xaml we must suddenly know what reference our class came from, also it won't find the reference for you, you either have to try all references to see if they have a certain class or find a code example."
If part of your question is more about how can you more-easily handle your XAML (or more appropriately xmlns) namespaces so that it is easier to get references ironed out in your XAML, there is a technique that you may find useful. It lets you consolidate namespaces so that you can use fewer XAML namespace prefixes (or even no namespace prefixes if you take this technique to its extreme).
"2. How to merge the ribbon menu with the application bar (the top bar on most windows applications)? So I get a nice Ribbon Application Menu, like in the example."
Essentially it seems that you're asking how to: (a) extend the window chrome area (the Aero glass area) down into the client part of the window (the part that your application normally gets to put things) and (b) extend the client part of the window up into the window chrome area. If you can do both of these things, then you can end up with something that looks like Microsoft office products or modern web browsers. Fortunately there is the WPF Shell Integration Library which helps you do both of these things. I found this blog and this blog (and the source code they offer) good guides for getting started with using the WPF Shell Integration Library.
Using this library, I was able to make this window (all but the Aero color changing abilities which is a whole other topic). Notice that both of qualities I mentioned are working here (the TabControl is being display up in the normal window chrome top bar area and the window chrome Aero glass is being displayed down in the normal client area):

Here's my take
1) What is the logic behind this all and how to figure out what to use
where?
Whatever you can fit between "" can go inline like:
<TextBlock Text="{Binding Name}" />
Whatever can't, go the element way:
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0} ({1})">
<Binding Path="Name" />
<Binding Path="Gender" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
2) How to merge the ribbon menu with the application bar (the top bar on
most windows applications)? So I get a nice Ribbon Application Menu,
like in the example.
You'll find more or less complicated mumbo jumbo around google, this is the essence of it:
<Window ...
WindowStyle="None" AllowsTransparency="True" Background="Transparent"
...>
<!-- Fill it up with a PNG image if you want to play with transparency -->
</Window>
Then make the ribbon the top element, and re-create Close/Maximize buttons
3) Is there a way to turn off xaml background compliation? I'd sacrifice
Intellisense for this.
Yep, it's called Notepad++

Related

UI Automation, Ribbon Control and Automation Anywhere 11 in WPF

I am building a new bot in Automation Anywhere 11 and I have found recently a tricky situation when I'm trying to automate the Windows Ribbon.
If I have only one tab everything works as expected and I can identify all buttons inside, but if I have multiple tabs only the last tab elements are visible to the Object Cloning option, I have added unique Names, AutomationIDs, etc. And nothing has worked. This is a preview of the issue:
This is my example XAML code:
<UserControl x:Class="Example.RibbonMenu"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
xmlns:my="http://schemas.microsoft.com/winfx/2006/xaml/presentation/ribbon">
<my:Ribbon x:Name="R1" AutomationProperties.AutomationId="R1ID">
<my:RibbonTab Header="Tab 1" x:Name="Tab1" AutomationProperties.AutomationId="Tab1ID">
<my:RibbonGroup x:Name="GB1" AutomationProperties.AutomationId="RG1ID">
<my:RibbonButton Label="Button 1" x:Name="RB1" AutomationProperties.AutomationId="RB1ID" />
</my:RibbonGroup>
</my:RibbonTab>
<my:RibbonTab Header="Tab 2" x:Name="Tab2" AutomationProperties.AutomationId="Tab2ID">
<my:RibbonGroup x:Name="RG2" AutomationProperties.AutomationId="RG2ID">
<my:RibbonButton Label="Button 2" x:Name="RB2" AutomationProperties.AutomationId="RB2ID" />
<my:RibbonButton Label="Button 3" x:Name="RB3" AutomationProperties.AutomationId="RB3ID" />
</my:RibbonGroup>
</my:RibbonTab>
</my:Ribbon>
</UserControl>
Also, I have read multiple options:
UI Automation and Ribbon control
XAML - Binding row and column index of cell to automation ID
Unable to generate Automation ID for WPF Controls, to be used by coded UI for automation testing
How can I find WPF controls by name or type?
Coded Ui test unable to find the WPF Ribbon button
How can i automate Ribbon UI
But nothing that I tried so far was worked until recently, I identified that the issue is connected to the last tab. Also, as I said in the comments section, I tried the Legacy Option and Manage Windows Controls too. Here are some previews:
Legacy Option Enabled:
Manage Windows Controls:
Furthermore, another ribboned app like Paint where the buttons are recognized:
Also, I have tested another Microsoft tool: AccExplorer32.exe, which shows exactly the same behavior, proving that this is not a limitation of AA or UiPath, but something from the coding perspective, here you have a preview:
Does anyone have an idea how to fix it? Or has experienced something similar? Thanks for your help.
P.S.
I'd not want an answer about Image Recognition or MetaBots (partial solution and quite good in the case of AA) as options since this is a programming issue and I'm interested to solve it.
I identified a second problem regarding the TabControl. If for any reason when you have only one TabItem active and you decide to hide the tab name for aesthetic reasons, my advice is to enable it for robots since if you hide it then the robot cannot find any elements inside and you might need a MetaBot, which wouldn't be as reliable as you want to.
Not working:
The tabs don't work even with MetaBots:
Working:
Also, I was able to find an example with Window Forms, Windows SDK and the regular ribbon from MS where it works as expected since the first time without any specific adjustment.
This is a partial solution if we cannot find a solution in WPF (I highly doubt, there is no possibility). Someone suggested I use a MetaBot, which is capable of screening the entire window, and yes, in this way, you're able to identify all controls that are visible (not in all tools, i.e., SAP without SAP scripting enabled, it's impossible).
However, I wouldn't recommend it since this won't solve major issues or bring stability in future changes or drastic ones from the screen or UI.
Also, I can suppose based on my experience that is going to be less efficient since in the "regular process" you are going to access a specific AutomationID of a unique control based on Object Cloning while in the MetaBot, you're going to constantly access the full screen to get all controls and later choose one by one using the logic you created and you will need to repeat the same actions each time for each screen and follow the same pattern for each action. Further, why do I think it's less efficient, you might ask because you're adding complexity to the solution.
If I find a better answer or solution, I'm going to add it as soon as I have it.
P.S.
It doesn't work for A2019. AA removed support for MetaBots and there is no current alternative besides image recognition.
For the time being, this is the only solution since neither Microsoft (they tried to silence me moving my question to the Off-Topic section and didn't reply my comment to move it back to the correct forum) nor AA (I had longs talks with them and they didn't want to take any responsibility or raise the ticket to MS for support) wants to help.
It's important to highlight that it's not necessary a reliable solution since the next version of Automation Anywhere v2019 it's a totally different tool based on different technologies that might not support everything "in the beginning" and could collapse all your robots and could lead to re-write your robots from scratch (I talked about this since they don't have proper migration tools).

Drag and drop from datasource to WPF window not working

I have been tasked to design a contact management program for my company. We have VS 2012 and since I have never used WPF before I thought I would use it to develop this application.
I am having huge problem getting started on the binding when utilizing the entity framework for the database which btw is database first.
I have followed the instructions within this link to the letter.
http://msdn.microsoft.com/en-us/data/jj574514.aspx
The objects show up in the data sources window just fine. But when I drag and drop to my window, nothing happens. No idea what I am doing wrong and cannot find anyone else with this problem.
Can anyone help me out here? I have looked everywhere. Any help is appreciated
Ok. I actually went thru that article, just to show good faith and let you know that I actually want to help you.
I came to the following conclusions:
That article show a very basic scenario of getting data from an Entity Framework context and showing it in a WPF DataGrid.
It doesn't have any kind of validation nor business rules.
It doesn't have any UI behavior such as conditionally enabling/disabling or showing/hiding any UI elements.
That kind of scenario is where the Designer is useful, when you don't actually need anything except getting / saving data from / to a DB.
Unfortunately (or fortunately for all of us developers who make a living of it), most applications will require some level of validation and business rules and some level of UI logic.
The designer is really useless when it comes to developing complex logic.
You can use the designer for such situations where you don't require complex logic, however I must warn you the following cons:
The Visual Studio WPF designer produces fixed-size, fixed-position UIs. these type of UIs don't work well when executed in computers with different screen resolutions and DPI settings. Just like winforms.
It also produces XAML that has many unnecessary things (such as x:Name="categoryIdColumn" and things like Margin="13,13,43,191" which are really bad from a maintainabilty / scalability point of view)
From what I've seen, the designer-generated XAML also contains a CollectionViewSource, this is both a good thing and a bad thing. It's a good thing because it enables Design-Time Data in the DataGrid, but it is also bad because it bloats your XAML with lots of unneeded things and introduces unnecessary <Window.Resources> that complicate things up.
Now, this is the very minimal XAML needed for that DataGrid, without Design-time data support:
<Window x:Class="MiscSamples.DesignTimeDataGrid"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="DesignTimeDataGrid">
<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False">
<DataGridTextColumn Header="Category Id" Binding="{Binding CategoryId}"/>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
</DataGrid>
</Window>
You see? It's actually faster to type that (much more so with the help of Intellisense) than what it takes for you to browse the property window and set these properties manually.
My suggestion is that you get familiar with XAML instead of insisting in the hard way to do things
Another very important aspect to keep in mind is that generally speaking, you don't put anything in code-behind in WPF because it's not needed, therefore that tutorial is actually going against the WPF Way of doing things, but that's Ok because it's actually an Entity Framework tutorial, not a WPF tutorial.
ease of development
You really need to reconsider what you call "ease of development". When it comes to UI development, I call "ease of development" to actually being able to do what I want with the UI without having to resort to shitty procedural code practices involving P/Invoke (whatever that means) and "owner draw" type of things for evertyhing.
WPF provides REAL ease of development as opposed to the fake ease of development exhibited by winforms
winforms lets you do everything with a designer (and this is just because the code the designer generates is actually so shitty that nobody would have ever used winforms if they didn't have the designer) but then when it comes to adding complex DataBinding or UI logic you're stuck with winforms' incapabilities forever.
WPF encourages manual XAML writing, not only because XAML is declarative (as opposed to the procedural winforms approach), but also because the levels of customizability and reusability are so high that a designer-centric approach does not make sense.
drag and drop is the easy way out
No it's not. It's actually the hard way. The easy way is to learn XAML and be able to do Things you can't even imagine to do with winforms.
If a designer-centric approach still makes sense to you, you may want to try Expression Blend
Automatically Create Data Grids from Your Models
Using a data source to drag and drop a template onto a WPF control is an excellent and fast way to get up and running!
Start by doing this: In your project create a folder named Models, then use either Entity Framework DB first or code by hand the models you want to show.
OR see discussion below on Object binding...
In that same folder create a dummy class that is a property for IEnumerable like this..
public IEnumerable<MyClassModel> MyCollection { get; set; }
From there go to the Main Visual Studio menu, to View/Other Windows/Data Source and click that link.
Click on Object and find the MyCollection property just created above.
Now open a user control or window in WPF but keep the datasources toolbox opened.
It should default to a DataGrid, but you can right click on the datasource and change it to detail, datagrid or select individual properties of the class it represents.
Simply drag that datasource onto the XAML's grid area. The right click on the new stuff you see and click reset to set the content to be the size of the entire window.
After having done this you will have code injected into the code behind of the view as follows in the window loaded event of that window, usercontrol etc.
// Do not load your data at design time.
if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
{
//Load your data here and assign the result to the CollectionViewSource.
System.Windows.Data.CollectionViewSource myCollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["Resource Key for CollectionViewSource"];
myCollectionViewSource.Source = your data
// }
Go back to the XAML and look for the CollectionViewSource KEY property that was also inserted when you dragged the property to the XAML. It looks like this:
Use the Key name in the code behind, and then "Bind" the CVS to your data source which is an enumerable of type MyClassModel it can live in the View Model or in the code behind of the view as you choose.
If you only use the CollectionViewSource to as the datacontext of the grid you do not need to implement INPC for any underlying collections! The CVS updates the view automatically everytime the source is updated! Once you get good at this you can create working View prototypes of data in 2 minutes! Forget hand-coding XAML that just takes too long.
Object Binding
Create a static class with a static method that returns something like this:
When using the datasource wizard choose the "Object" selection.
Click Ok and you should see something like this:
You have just mapped all of the properties into the data source definition.
For anyone finding this issue in VS 2022: as per this is written, VS 2022 has this known bug unable to drag and drop data source to XAML form.
More info: https://developercommunity.visualstudio.com/t/drag-a-a-table-from-datasource-and-drop-in-a-windo/1660788
UPDATE:
It says that the fix has been released on 15th June. You can try updating your VS 2022 to the latest.

How do I add a movable container to a WPF form?

WPF newbie so please be gentle.
Looking to rewrite an existing VFP app in C#/WPF
All forms have containers which in turn contain textboxes, labels, etc, etc.
Using this configuration allows the user to move the container and contained controls with the mouse, set up focal points within the container to enable zooming in and out of the form, etc.
So instead of adding controls directly to the WPF form, a movable container needs to be added first and the controls added to the container.
So where to begin?
You can try the AvalonDock library to see if it can satisfy your requirement.
It sounds like one of the main things you're looking for is to add drag-and-drop ability for standard WPF panels/containers. As Mash said, AvalonDock could be of use to you, especially if you're interested in docking the panels in certain positions. But I would also suggest you taking a look at options to just add dragability to standard WPF panels. This would be a lighter-weight option to get you started quickly, without having to worry about AvalonDock's constraints.
There are certainly many ways that you could implement drag-and-drop, but a very handy capability that I think is a good fit for this task is the concept of Attached "Behaviors". Attached Behaviors basically allow you to "add on" capabilities to existing WPF controls without needing to alter or extend the actual control. There are two basic types of attached behaviors. One uses WPF Attached Properties, and the other uses what is commonly referred to as "Blend" behaviors. If you just want to get started using a bahavior to solve your immediate problem, you don't necessarily need to understand all the nuances of these two approaches, but eventually you will probably find that both of these approaches have their place, so I'd suggest reading this post about them.
In particular, there is a Blend behavior called MouseDragElementBehavior that allows you to add drag-and-drop capability to WPF panels (the "e" and "d" here are xmlns namespace prefixes):
<Border Background="LightBlue" >
<e:Interaction.Behaviors>
<b:DragBehavior/>
</e:Interaction.Behaviors>
<TextBlock Text="Drag me around!" />
</Border>
In a similar vein, you mentioned zoomability, and there is another Blend behavior that may be of use for you for that as well.
Blend behaviors are very easy to add an element if you're using Expression Blend, but you can also use them with Visual Studio. To explain how to do this, see part of Laurent's post about his magnify behavior.

Approach for a multi-lingual WPF application

it seems there are a number of approaches on how to implement multiple languages in a WPF application. But I would like some more information about what method I should be using with the following requirements:
It's a PRISM application, so a number of independent modules (assemblies) working together. I would like that each assembly has its own translations of UI elements.
I need a simple approach, no tools needed to generate stuff
Should still be able to use blend to design the UI
Optionally be able to switch language without restarting the application (not a dealbreaker)
Can someone advice me on how to achieve this?
Thanks!
A common approach is to bind the text property of your textblocks / labels etc.. to some property on a statically defined localization resource:
<Label Content="{Binding Source={x:Static loc:LanguageContext.Instance},
Path=Dictionary, Mode=OneWay,
Converter={StaticResource languageConverter},
ConverterParameter=TextId}" />
i.e. LanguageContext.Instance exposes a dictionary via a property Dictionary, the Converter uses the given ConverterParameter to look up the text identified via TextId.
This is a cumbersome approach, and will not fulfil all your requirements.
A better method is to defined your own markup extension to perform this sort of logic. There are a couple of solutions I have seen on the web, this high rated codeproject article:
http://www.codeproject.com/KB/WPF/realtime_multilingual.aspx
And a similar solution here that provides Blend, on-the-fly language changes, so is probably a good choice for you:
http://blogs.microsoft.co.il/blogs/tomershamam/archive/2007/10/30/wpf-localization-on-the-fly-language-selection.aspx
With the above example you define an attached property which identifies the key of the translated item, and use the Translate markup extension to identify the properties which are translated.
NOTE: it is not just text which is being translated here, often you have to change colors / graphics etc ...
Meanwhile I found an open source project that works really well: http://wpflocalizeextension.codeplex.com. It's just adding a reference to the dll, adding the resources with translations, and using it in XAML. It worked in 5 minutes. I can add multiple resources to individual modules; and it works fine in visual studio designer and blend. And, locale can be changed on the fly. Meets my requirements :)

How to create databinding over two xaml files?

I am trying to come to a working understanding of how databinding works, but even after several tutorials I only have a basic understanding of how databinding works. Thus this question might seem fundamental to those more familiar with silverlight. Even if it is trivial, please point me to some tutorial that deals with this problem. All that I could find simply solved this via adding the data binding on a parent page.xaml (that i must not use in my case).
For the sake of this example let us assume, that we have 5 files:
starter.cs
button1.xaml + codeBehind
button2.xaml + codeBehind
The two buttons are generated in code in the starter(.cs) file, and then added to some MapLayer
button1 my_button1 = new button1();
button2 my_button1 = new button2();
someLayer.Children.Add(my_button1);
someLayer.Children.Add(my_button2);
My aim is to connect the two buttons, so that they always display the same "text" (i.e. my_button1.content==my_button2.content = true;). Thus when something changes my_button1.content this change should be propagated to the other button (two way binding).
At the moment my button1.xaml looks like this:
<Grid x:Name="LayoutRoot">
<Button x:Name="x_button1" Margin="0,0,0,0" Content="{Binding ElementName=x_button2, Path=Content}" ClickMode="Press" Click="button1_Click"/>
</Grid>
But everthing that i get out of that is a button with no content at all, it is just blank as the binding silently fails.
How could I create the databinding in the context I described? Preferably in code and not XAML ;)
Thanks in advance
The chunk of documentation you need to read is this: XAML Namescopes
Your button1 xaml has a binding looking for an element with the name "x_button2". However in a real application there can be many controls which in turn have nested controls. All of these controls have all manner of UI elements some of which may have names.
It would be impossible to get anything done if all names throughout the entire application had be unique. Yet that would need to be true if it were for your button1 to be able to hunt down the existence of another control somewhere in the visual tree outside of that which it actually knows (its own xaml).
Hence each loaded Xaml document exists in its own "namescope" and the search for other elements with other names is limited to that "namescope".
The are various solutions to this problem depending on what you real requirements are as opposed to the simplified problem in your question.
Typically you give each of your controls a DependencyProperty to which the inner button Content property binds. In "MapLayer" as call it, could then bind the propert on one of your button controls to the other.

Resources