How can a WPF UserControl inherit a WPF UserControl? - c#

The following WPF UserControl called DataTypeWholeNumber which works.
Now I want to make a UserControl called DataTypeDateTime and DataTypeEmail, etc.
Many of the Dependency Properties will be shared by all these controls and therefore I want to put their common methods into a BaseDataType and have each of these UserControls inherit from this base type.
However, when I do that, I get the error: Partial Declaration may not have different base classes.
So how can I implement inheritance with UserControls so shared functionality is all in the base class?
using System.Windows;
using System.Windows.Controls;
namespace TestDependencyProperty827.DataTypes
{
public partial class DataTypeWholeNumber : BaseDataType
{
public DataTypeWholeNumber()
{
InitializeComponent();
DataContext = this;
//defaults
TheWidth = 200;
}
public string TheLabel
{
get
{
return (string)GetValue(TheLabelProperty);
}
set
{
SetValue(TheLabelProperty, value);
}
}
public static readonly DependencyProperty TheLabelProperty =
DependencyProperty.Register("TheLabel", typeof(string), typeof(BaseDataType),
new FrameworkPropertyMetadata());
public string TheContent
{
get
{
return (string)GetValue(TheContentProperty);
}
set
{
SetValue(TheContentProperty, value);
}
}
public static readonly DependencyProperty TheContentProperty =
DependencyProperty.Register("TheContent", typeof(string), typeof(BaseDataType),
new FrameworkPropertyMetadata());
public int TheWidth
{
get
{
return (int)GetValue(TheWidthProperty);
}
set
{
SetValue(TheWidthProperty, value);
}
}
public static readonly DependencyProperty TheWidthProperty =
DependencyProperty.Register("TheWidth", typeof(int), typeof(DataTypeWholeNumber),
new FrameworkPropertyMetadata());
}
}

Ensure that you have changed the first tag in the xaml to also inherit from your new basetype
So
<UserControl x:Class="TestDependencyProperty827.DataTypes.DataTypeWholeNumber"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:s="clr-namespace:System;assembly=mscorlib"
>
becomes
<myTypes:BaseDataType x:Class="TestDependencyProperty827.DataTypes.DataTypeWholeNumber"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:s="clr-namespace:System;assembly=mscorlib"
xmlns:myTypes="clr-namespace:TestDependencyProperty827.DataTypes"
>
So, to summarise the complete answer including the extra details from the comments below:
The base class should not include a xaml file. Define it in a single (non-partial) cs file and define it to inherit directly from Usercontrol.
Ensure that the subclass inherits from the base class both in the cs code-behind file and in the first tag of the xaml (as shown above).

public partial class MooringConfigurator : MooringLineConfigurator
{
public MooringConfigurator()
{
InitializeComponent();
}
}
<dst:MooringLineConfigurator x:Class="Wave.Dashboards.Instruments.ConfiguratorViews.DST.MooringConfigurator"
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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:dst="clr-namespace:Wave.Dashboards.Instruments.ConfiguratorViews.DST"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
</Grid>
</dst:MooringLineConfigurator>

I found the answer in this article: http://www.paulstovell.com/xmlnsdefinition
Basically what is says is that you should define an XML namespace in the AssemlyInfo.cs file, which can the be used in the XAML. It worked for me, however I placed the base user control class in a separate DLL...

There is partial class definition created by designer, you can open it easy way via InitializeComponent() method definition.
Then just change partial class iheritence from UserControl to BaseDataType (or any you specified in class definition).
After that you will have warning that InitializeComponent() method is hidden in child class.
Therefore you can make a CustomControl as base clas instead of UserControl to avoid partial definition in base class (as described in one comment).

I ran into the same issue but needed to have the control inherit from an abstract class, which is not supported by the designer. What solved my problem is making the usercontrol inherit from both a standard class (that inherits UserControl) and an interface. This way the designer is working.
//the xaml
<local:EcranFiche x:Class="VLEva.SIFEval.Ecrans.UC_BatimentAgricole"
xmlns:local="clr-namespace:VLEva.SIFEval.Ecrans"
...>
...
</local:EcranFiche>
// the usercontrol code behind
public partial class UC_BatimentAgricole : EcranFiche, IEcranFiche
{
...
}
// the interface
public interface IEcranFiche
{
...
}
// base class containing common implemented methods
public class EcranFiche : UserControl
{
... (ex: common interface implementation)
}

Related

Generic Argument Constraint Violation?

I have declared a base dialog window class that types the datacontext to ensure that the attached viewmodel has the appropriate return type. When I try to use it though I get a generic arguments error:
GenericArguments[1],
'Mocks.MidSoft_Hospitality_ViewModels_Dialogs_ReceiveItemViewModel_32_569724456',
on
'Mocks.MidSoft_Hospitality_Views_Dialogs_BaseDialogWindow`2_32_569724456[TResult,TViewModel]'
violates the constraint of type 'TViewModel'.
I can't see why this would be happening
The base dialog window declaration:
public class BaseDialogWindow<TResult, TViewModel> : DialogWindowBase<TResult> where TViewModel: ViewModels.Dialogs.DialogBaseViewModel<TResult>
{
public BaseDialogWindow() : base()
{
}
new public TViewModel DataContext
{
get => this.GetValue(DataContextProperty) as TViewModel;
set => this.SetValue(DataContextProperty, value);
}
}
DialogWindowBase:
public class DialogWindowBase<TResult> : Window, IDialog<TResult>
{
public DialogWindowBase()
{
//Formatting code here
}
public Result Result { get; set; } = Result.None;
public TResult ReturnData { get; set; }
}
The viewModel:
public class ReceiveItemViewModel : ViewModels.Dialogs.DialogBaseViewModel<ReceiveItemResult>
{
//View Model Code here
}
and the xaml:
<local:BaseDialogWindow x:Class="MidSoft.Hospitality.Views.Dialogs.ReceiveItemDialog"
x:TypeArguments="local:ReceiveItemResult, vm:ReceiveItemViewModel"
xmlns:vm="clr-namespace:MidSoft.Hospitality.ViewModels.Dialogs"
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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MidSoft.Hospitality.Views.Dialogs"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance vm:ReceiveItemViewModel, IsDesignTimeCreatable=False}"
x:Name="ReceiveStockItemDialog"
Height="450" Width="800">
<Grid>
</Grid>
</local:BaseDialogWindow>
Code for the dialog:
public partial class ReceiveItemDialog
{
public ReceiveItemDialog()
{
InitializeComponent();
}
}
The error that I referenced above is the only compiler error that I am getting. I would appreciate any insight into this error.
Update: I have now noticed that the application is compiling and running without any exceptions being thrown but the error is still there and the xaml designer is showing it as invalid markup
IsDesignTimeCreatable=False will force the designer to ignore the specified DesignInstance type and create a substitute type using reflection. In this case the designer failed to recognize the generic type as it is a complex type rather than a primitive type and therefore failed to create a proper mock instance with a proper generic parameter TViewModel.
To solve this, you could set the IsDesignTimeCreatable property to True and implement a default constructor on ReceiveItemViewModel. If a default constructor is not possible, introduce a wrapper type just for the design time DesignInstance and spend it a a default constructor that initializes the base type ReceiveItemViewModel properly.

wpf c# data binding to set string using property of viewModel object

I am trying to solve this issue for so many hours:
I have user custom control of grid named NewMazeGrid and I want to use it as a control in MainWindow. MainWindow contains MazeViewModel(mazeVM member).
I'm trying to set the values of the grid, when the property MazeViewModel:MySingleplay changes.
(I'm using the INotifyPropertyChanged for it, and it works perfectly fine. I guess, the problem is in the final binding)
The code:
This is the property MazeViewModel:MySingleplay getter:
public string MySingleplay
{
get
{
if (myModel.MySingleplay == null)
{
return "";
} else
{
return myModel.MySingleplay.ToString();//works perfect
}
}
}
this is the NewMazeGrid.xaml.cs:
namespace VisualClient.View.controls
{
public partial class NewMazeGrid : UserControl
{
private MazePresentation myMaze;
private string order; //dont really use it
//Register Dependency Property
public static readonly DependencyProperty orderDependency =
DependencyProperty.Register("Order", typeof(string), typeof(NewMazeGrid));
public NewMazeGrid()
{
myMaze = new MazePresentation();
InitializeComponent();
DataContext = this;
lst.ItemsSource = myMaze.MazePuzzleLists;
}
public string Order
{
get
{
return (string)GetValue(orderDependency);
}
set
{
SetValue(orderDependency, value);
myMaze.setPresentation(value); //(parsing string into matrix)
}
}
}
}
this is the MainWindow.xaml.cs:
public partial class MainWindow : Window
{
private MazeViewModel mazeVM;
public MainWindow()
{
InitializeComponent();
mazeVM = new MazeViewModel(new ClientMazeModel(new TCPClientConnection()));
DataContext = mazeVM;
mazeVM.connectToServer();
}
private void bu_Click(object sender, RoutedEventArgs e)
{
bool isC = mazeVM.isConnected();
mazeVM.openSingleplayGame("NewMaze");//works perfect
}
this is the MainWindow.xaml:
<Window x:Class="VisualClient.View.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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:Controls ="clr-namespace:VisualClient.View.controls"
xmlns:vm ="clr-namespace:VisualClient.ViewModel"
xmlns:local="clr-namespace:VisualClient.View"
mc:Ignorable="d"
Title="Main Window" Height="350" Width="525" MinWidth="900" MinHeight="600">
<WrapPanel >
<Button Name ="bu" Content="Click_Me" Click="bu_Click"/>
<Grid Name="myGrid">
<Controls:NewMazeGrid Order="{Binding MySingleplay, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
</WrapPanel>
</Window>
I get this error on the binding line: Value cannot be null.
To sum:
It initialize fine the window in the ctor, but when the property changes it does not get into the Order property setter. therefor my grid never changes.
What should be the right syntax for binding in this case? how do I bind it to the right property?
Folders hierarchy explorer
WPF may not call the CLR wrapper of a dependency property, but just directly call the GetValue and SetValue methods of the underlying DependencyObject. This is why there should not be any logic except the GetValue and SetValue calls.
This is explained in XAML Loading and Dependency Properties:
Because the current WPF implementation of the XAML processor behavior
for property setting bypasses the wrappers entirely, you should not
put any additional logic into the set definitions of the wrapper for
your custom dependency property. If you put such logic in the set
definition, then the logic will not be executed when the property is
set in XAML rather than in code.
Similarly, other aspects of the XAML processor that obtain property
values from XAML processing also use GetValue rather than using the
wrapper. Therefore, you should also avoid any additional
implementation in the get definition beyond the GetValue call.
To get notified about property value changes, you can register a PropertyChangedCallback by property metadata. Note also that there is a naming convention for DependencyProperty fields. Yours should be called OrderProperty:
public static readonly DependencyProperty OrderProperty =
DependencyProperty.Register(
"Order", typeof(string), typeof(NewMazeGrid),
new PropertyMetadata(OnOrderChanged));
public string Order
{
get { return (string)GetValue(OrderProperty); }
set { SetValue(OrderProperty, value); }
}
private static void OnOrderChanged(
DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
((NewMazeGrid)obj).myMaze.setPresentation((string)e.NewValue);
}
Besides that, you must not set
DataContext = this;
in the constructor of NewMazeGrid. This effectively prevents inheriting the DataContext from the parent window, so that {Binding MySingleplay} won't work. Except under special circumstances you should never explicitly set a UserControl's DataContext.
So, remove the DataContext assignment from the constructor:
public NewMazeGrid()
{
myMaze = new MazePresentation();
InitializeComponent();
lst.ItemsSource = myMaze.MazePuzzleLists;
}
That said, there is also no need to set UpdateSourceTrigger=PropertyChanged on a one-way binding. It only has an effect in two-way (or one-way-to-source) bindings:
<Controls:NewMazeGrid Order="{Binding MySingleplay}"/>

C# web browser constructor

I am trying to add a web browser to an existing C# application, but, having not used C# in about 6 years, I am quite unfamiliar with how it works.
I am trying to add the browser to a partial class (again, something I am not familiar with) using the following code:
public partial class WebBrowser : WebBrowserBase{
public WebBrowser(){
...
}
...
}
However, I am getting a compile error on the constructor that says:
'WebBrowserBase' does not contain a constructor that takes 0 arguments
I Google'd this, and came across the following question on SO: C# Error: Parent does not contain a constructor that takes 0 arguments. I tried doing what was suggested in the answer to this, and changed my code to:
public partial class WebBrowser : WebBrowserBase{
public WebBrowser(int i) : base(i){
...
}
...
}
However, I then get a compile error that says:
'WebBrowserBase' does not contain a constructor that takes 1 arguments
So I'm guessing that this issue isn't to do with the number of arguments in the constructor... Can anyone explain what I'm doing wrong here?
If you have a look at WebBrowserBase Class it states that:
"This API supports the product infrastructure and is not intended to be used directly from your code."
And it seems that it doesn't have any public constructor - so you can't inherit from it. But if you don't want to create your own WebBrowser control (alter some of it's functionality), you should just use the default System.Windows.Forms.WebBrowser in a XAML View:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Width="525"
Height="350">
<WebBrowser HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</Window>
In Inheritance,
If Derived class contains its own constructor which not defined in Base class then this error Occurs
For Example:
class FirstClass
{
public FirstClass(string s) { Console.WriteLine(s); }
}
class SecondClass : FirstClass
{
public SecondClass()
{
Console.WriteLine("second class");
}
}
Output: Error:-'myconsole.FirstClass' does not contain a constructor that takes 0 arguments
To Run without Error:
class FirstClass
{
public FirstClass()
{
Console.WriteLine("second class");
}
public FirstClass(string s) { Console.WriteLine(s); }
}
class SecondClass : FirstClass
{
public SecondClass()
{
Console.WriteLine("second class");
}
}

How to use a C# custom subclass in XAML?

Here is my issue : I would like to use a subclass of SurfaceInkCanvas in my MyWindow.
I created a C# class like this :
namespace MyNamespace
{
public class SubSurfaceInkCanvas : SurfaceInkCanvas
{
private MyWindow container;
public SubSurfaceInkCanvas()
: base()
{
}
public SubSurfaceInkCanvas(DrawingWindow d) : base()
{
container = d;
}
protected override void OnTouchDown(TouchEventArgs e)
{
base.OnTouchDown(e);
}
}
}
And I would like to use it in my XAML window. Is it something like this ?
<MyNamespace:SubSurfaceInkCanvas
x:Name="canvas"
Background="White"
TouchDown="OnTouchDown"/>
Am I totally on the wrong way ?
You need to import an Xml Namespace in order to use classes...
<Window x:Class="Namespace.SomeWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> ... </Window>
Notice how the namespaces are imported. The default one (no prefix) can be whatever you want, but it's probably best to leave that to Microsoft's presentation namespace. Then there is the "x" namespace, which is the base xaml namespace (of course you could change the prefix, but you should leave it as it is).
So, in order to add your own namespace to it there are two ways of doing it (one if it's local).
CLR-Namespaces: xmlns:<prefix>="clr-namespace:<namespace>;Assembly=<assemblyName>"
URI-Namespaces: xmlns:<prefix>="<uri>"
In your case you'd probably want to set the prefix as "local" and use the CLR Namespace (since it is all you can use).
Import: xmlns:local="clr-namespace:MyNamespace;Assembly=???"
Usage: <local:SubSurfaceInkCanvas ... />
Alternatively, if these classes are inside of an external library, you can map your CLR-Namespaces to XML-Namespaces... see this answer for an explenation on that.
You need to add the namespace (xmlns:myControls), try like this:
<Window ...
xmlns:myControls="clr-namespace:MyNamespace;assembly=MyNamespace"
...>
<myControls:SubSurfaceInkCanvas x:Name="canvas"
Background="White"
TouchDown="OnTouchDown"/>
</Window>

Inherited Window can not have a name?

I'm having trouble with naming my Window which is inherited from its Base Window,
when I try to give a name to my Window I get following error.
The type BaseWindow cannot have a Name attribute. Values types and types without a default constructor can be used as items within ResourceDictionary.
XAML :
<log:BaseWindow
x:Class="EtraabMessenger.MainWindow"
x:Name="main"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:log="clr-namespace:EtraabMessenger.MVVM.View.Controls"
xmlns:VMCore="clr-namespace:EtraabMessenger.MVVM.VMCore"
VMCore:WindowClosingBehavior.Closing="{Binding DoCloseMainWindowCommand}"
Height="464" Width="279">
</log:BaseWindow>
EDIT : Here is my BaseWindow class
public abstract class BaseWindow : Window, INotifyPropertyChanged
{
protected BaseWindow()
{
// Note (Important) : This message should register on all windows
// TODO : I'm planning to move this registeration to BaseWindow class
Messenger.Register<bool>(GeneralToken.ClientDisconnected, DisconnectFromServer);
}
protected abstract void DisconnectFromServer(bool isDisconnected);
protected abstract void RegisterTokens();
protected abstract void UnRegisterTokens();
....
....
....
}
Any advice will be helpful.
Your base window apparently, as the error states, needs a public default contructor (one without arguments), it also may not be abstract because an instance of it needs to be created.

Categories