Designer rejecting DataTemplate.DataType - wpf

I am try to fit some WPF into my current Windows Forms application. When I use this simple user control, the designer for that control does not reload.
This only happens in this application. If I make a clean Windows Forms project, add these files, the designer works fine.
I have tried a reload of Visual Studio, and cleans / rebuilds of the application.
Any ideas? (These are for the items in a ListBox, so x:Key is not an option.)
P.S. How do I get rid of all those trailing blank lines in my code listing?
DETAILS:
MyClasses.cs
namespace MyNamespace {
internal class MyClassInternal {}
public class MyClassPublic {}
}
MyUserControl.xaml
<UserControl x:Class="MyNamespace.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyNamespace"
Height="300" Width="300">
<UserControl.Resources>
<DataTemplate DataType="{x:Type local:MyClassInternal}"/> <!--OK-->
<ObjectDataProvider x:Key="ClassPublicKey" ObjectType="{x:Type local:MyClassPublic}"/> <!--OK-->
<!-- Type reference cannot find public type named 'MyClassPublic' -->
<DataTemplate DataType="{x:Type local:MyClassPublic}"/> <!--FAILS-->
</UserControl.Resources>
<TextBlock>Hello World</TextBlock>
</UserControl>
MyUserControl.xaml.cs
using System.Windows.Controls;
namespace MyNamespace {
public partial class MyUserControl :UserControl {
public MyUserControl() {
InitializeComponent();
}
}
}

It was caused by having a space in the Assembly name.

Related

How do dependency properties work in WPF?

I'm trying to understand dependency property and learn how to use it. I'm going through articles and in this article https://www.c-sharpcorner.com/UploadFile/6d590d/wpf-dependency-property/ there's this example:
MainWindow.xaml:
<Window x:Class="WpfApplication1.DependencyPropertyDemo" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication1" Title="DependencyPropertyDemo" Height="350" Width="525">
<Window.Resources>
<ResourceDictionary>
<local:CarDependencyClass x:Key="carDependencyClass"></local:CarDependencyClass>
</ResourceDictionary>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Label Content="Enter Car:" Grid.Row="0" VerticalAlignment="Center" />
<TextBox Text="{Binding Path=MyCar, Source={StaticResource carDependencyClass }}" Name="MyTextCar" Height="25" Width="150" />
<Button Name="MyButton" Content="Click Me!" Height="25" Click="MyButton_Click" Width="150" Grid.Row="1" />
</Grid>
</Window>
MainWindow.xaml.cs:
using System.Windows;
namespace WpfApplication1 {
/// <summary>
/// Interaction logic for DependencyPropertyDemo.xaml
/// </summary>
public partial class DependencyPropertyDemo : Window {
public DependencyPropertyDemo() {
InitializeComponent();
}
private void MyButton_Click(object sender, RoutedEventArgs e) {
CarDependencyClass dpSample = TryFindResource("carDependencyClass") as CarDependencyClass;
MessageBox.Show(dpSample.MyCar);
}
}
public class CarDependencyClass : DependencyObject {
//Register Dependency Property
public static readonly DependencyProperty CarDependencyProperty = DependencyProperty.Register("MyProperty", typeof(string), typeof(CarDependencyClass));
public string MyCar {
get {
return (string)GetValue(CarDependencyProperty);
}
set {
SetValue(CarDependencyProperty, value);
}
}
}
}
It works. I noticed that they registered dependency property with the name "MyProperty" and that it isn't used anywhere in the program. Only normal CLR property MyCar is used in xaml.
But then there's another article https://www.c-sharpcorner.com/article/simplest-wpf-dependency-property-for-beginners-on-background-color/. And they provide other example:
MainWindow.xaml:
<Window x:Class="DependencyPropertyTutorial.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:views="clr-namespace:DependencyPropertyTutorial" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:DependencyPropertyTutorial" mc:Ignorable="d" Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<SolidColorBrush x:Key="BG" Color="Green" />
</Window.Resources>
<Grid>
<views:CustomButtonControl SetBackground="{DynamicResource BG}"></views:CustomButtonControl>
</Grid>
</Window>
CustomButtonControl.xaml:
<UserControl x:Class="DependencyPropertyTutorial.CustomButtonControl"
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:DependencyPropertyTutorial"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<Button x:Name="btnCustom" Content="Button" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="75" Height="52" Click="btnCustom_Click" />
</Grid>
</UserControl>
CustomButtonControl.xaml.cs:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace DependencyPropertyTutorial {
/// <summary>
/// Interaction logic for CustomButtonControl.xaml
/// </summary>
public partial class CustomButtonControl : UserControl {
public CustomButtonControl() {
InitializeComponent();
}
public static readonly DependencyProperty btnDependencyProperty = DependencyProperty.Register("SetBackground", typeof(SolidColorBrush), typeof(CustomButtonControl), new PropertyMetadata(new SolidColorBrush(Colors.HotPink), new PropertyChangedCallback(OnSetColorChanged)));
public SolidColorBrush SetBackground {
set {
SetValue(btnDependencyProperty, value);
}
get {
return (SolidColorBrush)GetValue(btnDependencyProperty);
}
}
private void btnCustom_Click(object sender, RoutedEventArgs e) {
this.SetBackground = new SolidColorBrush(Colors.IndianRed);
}
private static void OnSetColorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
CustomButtonControl mycontrol = d as CustomButtonControl;
mycontrol.callmyInstanceMethod(e);
}
private void callmyInstanceMethod(DependencyPropertyChangedEventArgs e) {
btnCustom.Background = (SolidColorBrush)e.NewValue;
}
}
}
And here they register dependency property with the name "SetBackground" which is exactly the same as the name of CLR property - SetBackground. And if I change dependency property(the one I registered with Register method) "SetBackground" to something else, like "SetBackgroundDependencyProperty", then I get a XAML exception when trying to run the application. But "SetBackground" dependency property isn't even referenced in xaml anywhere. Only CLR property SetBackground is referenced in XAML at the line
<views:CustomButtonControl SetBackground="{DynamicResource BG}"></views:CustomButtonControl>
I also get an error in Visual Studio with this example:
But when I try to build and run the application, it works.
So my questions are: why in the first example they didn't have to name registered dependency property the same as CLR property, but in the second example, I have to name registered dependency property the same as CLR property. Is there a way to name registered dependency property differently to the CLR property in the second example? Why and how xaml even uses dependency properties, considering xaml references only CLR properties anyway? I checked it and in both projects only CLR properties are referenced from XAML, according to VS IntelliSense. Why do I have to register dependency property with the same name as CLR property - "SetBackground" when in xaml only CLR property is referenced and it returns SolidColorBrush from the dependency property, anyway:
return (SolidColorBrush)GetValue(btnDependencyProperty);
Here's the solution with both examples:
https://github.com/KulaGGin/DependencyProperty
First example is a bit dirty, I wouldn't code it such way. There is a good convention to avoid a confusion - to name the DP as the CLR property + 'Property'(but it's not mandatory!) and register it as name of CLR property(if you want to use it as DP in XAML).
First to your questions:
First example does work, because of everywhere, where the property MyCar being used, it is used as CLR property. If you will try to bind to the MyCar, it will fail, because of there is no such a dependency property. To implement the functionality in this example would be enough just to declare a CLR property:
public string MyCar { get; set; }
instead of all this confusion with dependency property.
In second example CLR property as well as dependency property SetBackground are defined (the name btnDependencyProperty for the field is not convenient, but OK). Missunderstanding on your side, is what being used in XAML.
If you use in XAML Binding or DynamicResource the dependency property as well as CLR property are necessary! Therefore they need to have the same name. If there aren't, then you will get an error.
If you set the property to the StaticResource or directly to the value or even do not use it in XAML, then you will be able to run the application.
DependencyProperty implementation is slightly weird.
The XAML compiler depends on the CLR property wrapper in order to compile, but at runtime bindings ignore it completely and just call GetValue/SetValue on the DP. Therefore the names should match.
There was a typo in the first example. The registered dependency property name needs to be the same as the CLR-backing property.
Declaring a DependencyProperty is a two-stage process:
Register the property so that the WPF DependencyProperty system can track it and notify when properties change, etc.
Setup a CLR property that gives developers an API to get and set values.
I hope this helps.

WPF:programmatically add RibbonBar from UserControl into a RibbonWindow RibbonTab

I have a WPF Ribbon based application and a DLL.
In the application I uses a third party source (Syncfusion) to create my RibbonWindow.
The DLL is a WPF class library that consist of a UserControl which is a RibbonBar.
I would like to add that UserControl to my RibbonWindow.
I'm not sure how to do that programmatically.
MainWindow.xaml.cs
Dynamically loaded the UserControl from the DLL
Assembly asm = Assembly.LoadFile( unitDllPath );
Type typ = asm.GetType( "WX" + ".UserControl1", true, true );
unitDll = Activator.CreateInstance( typ );
MainWindow.xaml
<syncfusion:RibbonTab Name="Tab1" IsChecked="True" >
</syncfusion:RibbonTab>
UserControl.xaml
<syncfusion:RibbonBar Header="Select" Name="Bar1" ></syncfusion:RibbonBar>
UserControl.xaml.cs
public void MainWindow()
{
InitializeComponent();
}
How can I get the RibbonBar from WX.UserControl (Bar1) into (Tab1)?
Thanks.
1)If we need to programmatically add UserControl which is a RibbonBar to your RibbonWindow, your UserControl should be like below
UserControl.xaml
<syncfusion:RibbonBar x:Class="WPFClassLibrary.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:syncfusion="http://schemas.syncfusion.com/wpf"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<syncfusion:RibbonButton SizeForm="Large" Label="New Email"/>
<syncfusion:RibbonButton SizeForm="Large" Label="Inbox"/>
<syncfusion:RibbonButton SizeForm="Large" Label="Drafts"/>
<syncfusion:RibbonButton SizeForm="Large" Label="OutBox"/>
2)Refer the assembly file in your application.
3)use that Assembly in code behind like below
using WPFClassLibrary;
4)now we can call that UserControl from code behind and add to the our RibbonWindow.
tab1.Items.Add(new UserControl1());
i have also attach simple sample for this
http://www.syncfusion.com/downloads/support/directtrac/general/ze/WPfRibbonSample-1343767783

VS2013 : can't locate custom control resource on xaml page

I just installed vs2013 and I carried a WPF project, previous developed with VS2010, under this environment. Happens to me a very strange thing that obviously does not happen with 2010 .... I have my own custom control that defines a runtime URI to a dictionary ... the strangeness lies in the fact that in the code of xaml page, when i define the use of my control, i've got the error reported in subject, but if i start the dubug, everything works fine and the style is correctly applied .... someone got an idea?
the code look like that :
the custom control
using System;
using System.Windows.Controls;
using System.Windows;
using System.ComponentModel;
using System.Windows.Data;
namespace myListView
{
public class myListView : ListView
{
// ... some dependency property
protected override void OnInitialized(EventArgs e)
{
Uri uri = new Uri("Skins\\myDictionary.xaml", UriKind.Relative);
dictionary = Application.LoadComponent(uri) as ResourceDictionary;
//... rest of code
base.OnInitialized(e);
}
}
}
the xaml page
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:xlw="clr-namespace:myListView;assembly=myListView"
Title="MainWindow" Height="350" Width="525">
<Grid>
<xlw:myListView>
<!-- the editor tell me that can't find the Skins/myDictionary.xaml -->
</xlw:myListView>
</Grid>
</Window>

How to add UserControl to a Panel on a WPF Window

I think I'm missing something that should be obvious here, but I'm drawing a blank on this one.
I've built a very primitive UserControl containing nothing more than a TextBox to use as a log window:
<UserControl x:Class="My.LoggerControl"
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"
x:Name="LoggerView">
<Grid x:Name="LayoutRoot">
<TextBox x:Name="LogWindow" AcceptsReturn="True"/>
</Grid>
</UserControl>
I don't expect that to be the best way to do it, but it should be good enough for a prototype.
The code-behind is similarly simple:
public partial class LoggerControl : UserControl, ILogger
{
public LoggerControl()
{
InitializeComponent();
}
private LogLevel level = LogLevel.Warning;
#region ILogger
public LogLevel Level
{
get { return level; }
set { level = value; }
}
public void OnError(string s)
{
if (level >= LogLevel.Error)
LogWindow.AppendText("ERROR:::" + s + "\n");
}
// ...
#endregion
}
The thing I can't figure out is how to add this control to my MainWindow.xaml. Simplifying, lets say my window looks like this:
<Window x:Class="My.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:My"
Title="Test" Height="350" Width="525">
<Grid>
<local:LoggerControl x:Name="LogView" />
</Grid>
</Window>
Even with something so simple, the Designer in Visual Studio 2010 can't load the main window. The error given is:
A value of type 'LoggerControl' cannot be added to a collectionor dictionary of type 'UIElementCollection'.
This error message has only one unrelated hit in the major search engines (plus duplicates) so I haven't found any useful help. Microsoft's own documentation seems to imply that this should work.
Any idea how to solve this?
<UserControl x:Class="My.LoggerControl"
xmlns:local="clr-namespace:My.LogTest"
Looks like you may have made a mistake in the namespacing? LoggerControl is listed as being the namespace My, while you're importing My.LogTest and assigning it to the xml-prefix local. Change this to:
xmlns:local="clr-namespace:My"
And I think it should work. Otherwise, fix the LoggerControl declaration.

WPF binding set before application starts does not notify?

In theory this code should provide me with a 300x300 window with a blue background from having the window's content bound to an object of type AstRootViewModel, however this doesn't seem to be the case. I'm wondering it this is happening because I don't call astApplication.Run() until after I set the mainWindow.ViewModel property. Using snoop to check the binding I have a blank content binding and it's flagged as an error with no error information.
If it is the case that property notification does not occurr until the application Run method is called, then what would be the best way to resolve this in an MVVM friendly way?
I have the following Entry point to a WPF application:
[STAThread]
public static void Main()
{
settingsSource = LoadSettingsFile(".\\applicationSettings.xml");
astApplication = new Application();
mainWindow = new AstWindowView();
mainWindowModel = new AstRootViewModel();
dataModel = new AstDataModel(settingsSource);
mainWindow.ViewModel = mainWindowModel;
astApplication.MainWindow = mainWindow;
astApplication.Run();
}
The AstWindowView class implements the following significant code behind:
public partial class AstWindowView : Window
{
public AstRootViewModel ViewModel
{
get { return (AstRootViewModel)GetValue(ViewModelProperty); }
set { SetValue(ViewModelProperty, value); }
}
// Using a DependencyProperty as the backing store for ViewModel. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ViewModelProperty =
DependencyProperty.Register("ViewModel", typeof(AstRootViewModel), typeof(Window), new UIPropertyMetadata(null));
public AstWindowView()
{
InitializeComponent();
}
}
and the following significant XAML
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="AstViewResources.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Window.Content>
<Binding Path="ViewModel" Mode="Default" UpdateSourceTrigger="PropertyChanged"/>
</Window.Content>
The AstViewResources.xaml file defines the following DataTemplate
<DataTemplate DataType="{x:Type vm:AstRootViewModel}">
<vw:AstRootView/>
</DataTemplate>
And lastly, the AstRootView XAML contains the following significant XAML:
<UserControl x:Class="SEL.MfgTestDev.AutomatedSettingsTransfer.View.AstRootView"
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"
d:DesignHeight="300" d:DesignWidth="300">
<Grid Background="#FF000CFF"/>
</UserControl>
It looks like you're not setting the DataContext for AstWindowView anywhere and your Binding has no explicit Source set. Are you seeing a binding error saying something to that effect in your debug output? Try adding after the InitializeComponent call in AstWindowView ctor (could also do it by changing the Binding in XAML):
DataContext = this;

Resources