Problems with adding EnumMatchToBooleanConverter to my xaml file - c#

I am trying to follow this radiobutton tutorial
I created a class called EnumMatchToBooleanConverter and it is in the top level of my wpf project. It says to place the inside a window.resources like this:
<Window.Resources>
<EnumMatchToBooleanConverter x:Key="enumConverter" />
</Window.Resources>
I am using it in a usercontrol so I have placed it inside a stackpanel instead:
<StackPanel.Resources>
<EnumMatchToBooleanConverter x:Key="enumConverter" />
</StackPanel.Resources>
I have Microsoft Visual Studio Ultimate 2012 and it gives me an error:
EnumMatchToBooleanConverter is not supported in a Windows Presentation Foundation (WPF) project.
Any ideas as to what I am doing wrong? Am I not allowed to place it inside a stackpanel.resources?
I just tried placing it inside a grid.resources
<Grid.Resources>
<EnumMatchToBooleanConverter x:Key="enumConverter" />
</Grid.Resources>
and it says
The type 'EnumMatchToBooleanConverter' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built.
Well it is in the same namespace as the rest of my project, so I'm unsure why it isn't finding it.

Change
<EnumMatchToBooleanConverter x:Key="enumConverter" />
for
<local:EnumMatchToBooleanConverter x:Key="enumConverter" />
All non-built-in classes you reference in XAML must be prefixed by their corresponding xmlns prefix.

HighCore's got it right. Just to add to this namespace discussion, I thought I'd point out another approach that can help make the code more readable or help you diagnose where certain Controls/Value Converters/etc are coming from (i.e., which assembly they are really coming from). This technique could allow your XAML to appear like Christian has it in his blog (without the xmlns prefix):
<EnumMatchToBooleanConverter x:Key="enumConverter" />
Essentially you perform some some namespace mappings to consolidate namespaces like this (only works if the files are in a different assembly/project). So in my example above you have mapped one of your namespaces to the default xmlns, so you would not need any prefix in the XAML.
I'm still trying to figure out how far to take this technique and Paul Stovell talks about taking it to the extreme, like I've shown above.
Even if you don't end up applying it to that degree, knowing about it might come in handy if you're looking at someone else's Xaml and they have applied a mapping like that. Knowing that would remind you to lookup the AssemblyInfo.cs file and check for the mapping and possibly help you track down where a Control/Value Converter/etc is actually located.

Related

Better overview of visual WPF resources

Given: there are several resource dictionaries in WPF solution with various resources (vector graphics):
<ResourceDictionary ...>
<Canvas x:Key="SvgWarning" ... />
<Canvas x:Key="SvgError" ... />
<Canvas x:Key="SvgOk" ... />
...
<Path x:Key="PathBullet" ... />
<Path x:Key="PathMinus" ... />
...
Dictionaries are added to application resources. Those vector graphics are then used in different windows, user controls, etc.
Problem: over years of development they become too many. It's hard to tell how exactly which one looks like and I'd like to have better overview of them. E.g. if I'd have jpg-files referenced by a project then I could simply use windows explorer to preview how each looks like.
Currently I have to remember (or find) keys and then type it:
and only then I can see how it looks like. Silent intellisense is not a real problem (but a bonus points of course), because I simply want to preview images even before I decide to add one to a button.
Question: how can I organize it so I can quickly see which "witch" is which?
I can make a designer-only window (not used at run-time) and add all images there MANUALLY; by clicking each I can then see its key in xaml. Can I enumerate resources, detect which one is image (but not e.g. a style) and add it to such window? Maybe the way it's organized now is bad?
I don't need a concrete solution, rather a push in the right direction, hints from someone who has similar problem and have solved it.

XAML Forms not recognizing local and referenced classes

I opened a VS 2012 Solution in VS 2015 and cannot get it to compile. It was originally targeting .Net 3.5 and used the WPF Toolkit, which caused some ambiguous references. I resolved that by removing the reference to the WPF Toolkit and replacing it with the package DotNetProjects.Wpf.Toolkit.
Now I have to tackle the next issue, which I suspect is not caused by the obvious but is a cascade from some other hidden gotcha from upgrading the versions.
My XAML forms are not recognizing the existence of classes within referenced namespaces. I can get them to come up on intellisense but the application won't compile and the error says something like: "The name "MainWindow" does not exist in the namespace "clr-namespace:FieldSheetPrinter".
I have defined my main form with the following:
<Window
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"
xmlns:local="clr-namespace:FieldSheetPrinter"
mc:Ignorable="d"
xmlns:Custom="http://schemas.microsoft.com/netfx/2009/xaml/presentation"
xmlns:validationRules="clr-namespace:SWallTech.ValidationSupport;assembly=SWallTech.ValidationSupport"
xmlns:FieldSheetPrinter_Converters="clr-namespace:FieldSheetPrinter.Converters"
xmlns:Converters="clr-namespace:SWallTech.WPF.Support.Converters;assembly=SWallTech.WPF.Support"
x:Class="FieldSheetPrinter.MainWindow"
x:Name="MainWindow"
Title="CAMRA Field Sheet Printer - Stonewall Technologies, Inc."
Width="744"
Height="583"
WindowStartupLocation="CenterScreen"
Icon="CamraPrint.ico">
I have references to the SWallTech.WPF.Support project, which is in the solution, and the compiler has no problem recognizing the classes in that project's Converters namespace. This code has no error indicator. (Red squiggles.)
<Converters:IntGreaterThanZeroToVisibilityConverter
x:Key="IntGreaterThanZeroToVisibilityConverter" />
<Converters:DatabaseConnectionImageSourceConverter
x:Key="DatabaseConnectionImageSourceConverter" />
However if I try to refer to the ViewModel I am using as the datasource, I get an error:
<local:FieldSheetPrinterViewModel
x:Key="FieldSheetPrinterViewModelDataSource"
d:IsDataSource="True" />
I also get the error that the XAML form itself is not in the namespace FieldSheetPrinter, which of course it is, as you can see from the Code-Behind.
namespace FieldSheetPrinter
{
public partial class MainWindow : Window
...
}
I have tried everything I can think of, and I am truly stumped.
Joey
As suggested above, the problem wasn't directly with the XAML, or at least not completely. The original developer had named the Window tag with the same name as the code-behind class name, and that seems to be prohibited now. That was the only issue with the XAML. Everything else had to do with overlaps in the WPF and Windows.System.Data libraries that caused IValueConverter (in the System.Windows.Data namespace) to go unrecognized. I eliminated any other references that could have conflicted, and corrected some syntax issues in the code-behind that apparently were deprecated.
Ex.
stringVariable.IsNullOrEmpty()
was used instead of
string.IsNullOrEmpty(stringVariable)
In other places some ObservableCollection objects weren't recognized as enumerable, so I had to add "ToList()" before looping through the collection.
Weird, but I didn't write this stuff!
Thanks for the suggestions.
Joey

Error Occurred Loading Resource Dictionary

I've looked at and tried these other solutions that I've found, and even copied Telerik's Documentation. However, I still can't get a working solution.
XAML:
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="NotifyIconResources.xaml" />
<ResourceDictionary Source="pack://application:,,,/Telerik.Windows.Themes.Windows8;component/Themes/System.Windows.xaml" />
<ResourceDictionary Source="pack://application:,,,/Telerik.Windows.Themes.Windows8;component/Themes/Telerik.Windows.Controls.xaml" />
<ResourceDictionary Source="pack://application:,,,/Telerik.Windows.Themes.Windows8;component/Themes/Telerik.Windows.Controls.Navigation.xaml" />
</ResourceDictionary.MergedDictionaries>
Here is an image of the error that ReSharper is giving:
Here's an image of the assembly being a reference:
Here's an image of the assembly properties:
Lastly, here's the exception information when I try to run the app:
System.Windows.Markup.XamlParseException was unhandled
HResult=-2146233087
Message='Cannot create unknown type '{clr-namespace:Telerik.Windows.Controls.External}Windows8ThemeExternal'.' Line number '15' and line position '6'.
Source=PresentationFramework
LineNumber=15
LinePosition=6
StackTrace:
at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
at MyApp.App.InitializeComponent() in App.xaml: line 1
at MyApp.App.Main() in c:\MyApp\obj\Debug\App.g.cs: line 0
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Xaml.XamlObjectWriterException
HResult=-2146233088
Message='Cannot create unknown type '{clr-namespace:Telerik.Windows.Controls.External}Windows8ThemeExternal'.' Line number '15' and line position '6'.
Source=System.Xaml
LineNumber=15
LinePosition=6
StackTrace:
at System.Xaml.XamlObjectWriter.WriteStartObject(XamlType xamlType)
at System.Xaml.XamlWriter.WriteNode(XamlReader reader)
at System.Windows.Markup.WpfXamlLoader.TransformNodes(XamlReader xamlReader, XamlObjectWriter xamlWriter, Boolean onlyLoadOneNode, Boolean skipJournaledProperties, Boolean shouldPassLineNumberInfo, IXamlLineInfo xamlLineInfo, IXamlLineInfoConsumer xamlLineInfoConsumer, XamlContextStack`1 stack, IStyleConnector styleConnector)
at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
InnerException:
The first thing that I know IS wrong and that has to be added, according to Telerik documentation,
They can be merged in the resources of your application (in App.xaml) and as a result will be applied implicitly on any control that does not have a local Style set. For example, if you need to style a control from Telerik.Windows.Controls.dll, you need the Telerik.Windows.Controls.xaml resource dictionary.
That being said you're missing a ResourceDictionary for DataVisualization. If that doesn't solve the problem, keep reading.
Last I recall, when I was looking at theme'ing my application using Telerik, there are a couple different ways you can apply styles, and doing it right might be a little tricky at first. There is Implicit Styling (NoXaml) and there is standard styling, where styles are built into the control libraries. Implicit styling is the recommended approach for styling your application in a "global" manner. IIRC, it is also more performant is much more clean in code.
Since we talked in the WPF chat, it sounds like you weren't sure which binaries you were trying to build from source. Implicit styles requires you to build the Binaries.NoXaml source code. After that's said and done, you have to make sure you're adding references to the correct assemblies coming from the ..\Binaries.NoXaml\WPF4x\ directory.
The last time I built from source, the build instructions were included inside the downloaded .ZIP. Make sure you follow those instructions carefully. I have no used built in Visual Studio Telerik tools to build/deploy my referenced libraries, so if you are, then maybe manual is the way to go.
A couple other things. I'm suspicious the build wasn't successfully completed. Your Version # on your Telerik references should be something other than 0.0.0.0. Secondly, if I remember correctly, I had problems with defining the source and possibly the order matters--so try the source that I used in my example below, and maybe move the NotifyIconResources.xaml below the Telerik declarations.
Here is my XAML used with implicit style technique:
<ResourceDictionary Source="/Telerik.Windows.Themes.Windows7;component/Themes/Telerik.Windows.Controls.xaml" />
<ResourceDictionary Source="/Telerik.Windows.Themes.Windows7;component/Themes/System.Windows.xaml" />
<ResourceDictionary Source="/Telerik.Windows.Themes.Windows7;component/Themes/Telerik.Windows.Controls.Input.xaml" />
<ResourceDictionary Source="/Telerik.Windows.Themes.Windows7;component/Themes/Telerik.Windows.Controls.Navigation.xaml" />
As always, starting a new project and getting a basic thing like this working might do you wonders and it will also prevent you from changing so many things in your current code base that you end up forgetting the things you've changed and causing issues in places you don't want them.

How to set the Edge label in GraphX

I am using GraphX in Winform project. I am trying to display labels besides the edges. I want to know what property do I have to set in order to display some text in the label.
I have tried setting the 'Text' property of DataEdge, and then calling
ShowAllEdgesLabels(true);
but it does not work this way. Going through the forums I have found that WPF has a way to bind this property to the visual control. The XAML code is as follows
<gxl:EdgeLabelControl x:Name="PART_edgeLabel" Content="{Binding Edge.Text, RelativeSource={RelativeSource TemplatedParent}}" />
Now the question is what is the equivalent of Winform to achieve this functionality.
I found a solution with the help of the admin at the host of GraphX (PantheR).
Basically, we need to add the hostControler for WPF in a windows form.
We need to add a custom XAML template in the resources folder.
We need to load the XAML as a new resource in the code, before we initialize the graph.
We need to add a line of code to merge the resources.
Then in the XAML code we do the binding as mentioned in the question. The code has been updated at the repository to reflect these changes.
The downfall of this solution is that, we need to provide a XAML resource file with the program, but thats just another resource (in my opinion).
For anyone that need some reference code from #ResVic's answer:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:graphx="http://schemas.panthernet.ru/graphx/"
xmlns:local="clr-namespace:YOUR_NAME_SPACE">
...
<Style TargetType="{x:Type graphx:AttachableEdgeLabelControl}">
<Setter Property="ShowLabel" Value="False" />
</Style>
...
</ResourceDictionary>
The Show case demo is protentially helpful for figuring out what stuff the lib could do and how to tweak it to work.

WPF Basics: Shared global styles for MVVM

I am attempting to use an MVVM-ish approach to my WPF development.
I have my logical view model classes under the ViewModel namespace, and I have matching styling for these view model classes under the View namespace.
For now I have my View information in ResourceDictionary XAML files, as DataTemplates and Styles, which are all merged into the single App.Resources ResourceDictionary in app.xaml.
However, I'm running into a sort of chicken/egg problem. I want there to be global styles that I use all over the place. For example, I want my own custom text style called MonkeyText which could be used in various stylings all over the place. I can't just set this in the app.xaml file, because the resourcedictionarys that will want to use MonkeyText are included by that app.xaml file.
I guess if that's impossible an alternative would be to use UserControls instead of mostly using DataTemplates to establish my views? I'm afraid that using UserControls would tie the VM and V parts too closely together.
WPF provides DynamicResources for just this reason. StaticResources - which most resemble 'traditional' references in programming - have just the problem you encountered; they need to be defined and loaded prior to the point that a style is parsed. DynamicResources, on the other hand, do not need to be defined prior to the point they are used - indeed, you can even create them on the fly. WPF takes care of ensuring that DynamicResources are automatically loaded by all of the styles that reference them once they are actually loaded.
Using DynamicResources is straightforward. When you create your MonkeyText style, create it as you normally would:
<Style TargetType="TextBlock" x:Key="MonkeyText">
<Setter Property="TextAlignment" Value="Center"/>
<!-- etc. -->
</Style>
And then refer to it from elsewhere using a DynamicResource:
<TextBlock Text="Hello, World!" Style="{DynamicResource MonkeyText}"/>
If, for any reason, WPF cannot resolve your DynamicResource, it will fail silently without any exception thrown (StaticResources do throw exceptions when the cannot be resolved). It will, however, print a debug message when this happens - so keep an eye on the Output window in Visual Studio.
Since DynamicResources work with resources that are loaded at any point in any order, you can structure your resource dictionaries any way you like - so putting them in with your other View styles and merging them in via the single App.Resources ResourceDictionary in app.xaml will work fine.
More details on DynamicResources can be found in the MSDN docs for WPF.

Categories

Resources