Subclassing WPF Window - wpf

I created a WPF Window
than i modified its class definition to:
public partial class myWindow : mySubclassedWindow
compiler throws:
"Partial declarations of 'myWindow' must not specify different base classes"
myWindow.Xaml:
x:Class="WpfGridtest.myWindow"
so somewhere, there is another partial class, that inherits from "Window" but i cannot find it. How can i override my case to use subclassed window?
thanks Jon, that was the problem.
also found this helpful article:
http://geekswithblogs.net/lbugnion/archive/2007/03/02/107747.aspx

That would be in the declaration of myWindow itself - the designer will be generating the other half of the partial type based on the XAML, based on your element type.
You can use an element of <mySubclassedWindow> instead, so long as you give it the appropriate namespace and assembly references.
EDIT: Okay, so here's a short example, in a project called WpfApplication. My Window subclass:
using System.Windows;
namespace WpfApplication
{
public class EnhancedWindow : Window
{
}
}
My XAML:
<y:EnhancedWindow x:Class="WpfApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:y="clr-namespace:WpfApplication"
Title="MainWindow" Height="350" Width="525">
</y:EnhancedWindow>
My partial type:
namespace WpfApplication
{
public partial class MainWindow : EnhancedWindow
{
public MainWindow()
{
InitializeComponent();
}
}
}
It all builds with no problem. I think that's what you wanted to do, right?

Related

Generic ReactiveUserControl "cannot be edited in Design view"

I changed my UserControl to be a ReactiveUserControl and now I can't view the Design View. Is there anything I can do to get the designer to work with ReactiveUserControl?
The Visual Studio designer has issues when your control or window directly inherits from a generic class. This was a pretty common issue with WinForms as well. You can work around this issue by defining another non-generic class that sits between the generic ReactiveUserControl and your control:
public partial class MyUserControl : MyUserControlBase
{
public MyUserControl()
{
InitializeComponent();
}
}
public abstract class MyUserControlBase: ReactiveUserControl<MyUserControlViewModel>
{
}
In the XAML, our root object element is defined as the base element (MyUserControlBase) and its class declaration is connected to the partial class defined above (MyUserControl):
<myNameSpace:MyUserControlBase
x:Class="MyNameSpace.MyUserControl"
xmlns:myNameSpace="clr-namespace:MyNameSpace"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

Calling a custom dependency property defined in code-behind from XAML

Is it possible to call a custom dependency property in the XAML of the element in which it is defined?
I mean, i have the following simple code for my mainWindow:
Code
public partial class MainWindow : Window
{
public static readonly DependencyProperty SpecialToProperty = DependencyProperty.Register("SpecialTo", typeof(double), typeof(MainWindow));
public MainWindow()
{
InitializeComponent();
}
public double SpecialTo
{
get
{
return (double)GetValue(SpecialToProperty);
}
set
{
SetValue(DoubleAnimation.ToProperty, value);
}
}
}
How can i use that dependency property from the XAML partial code of the MainWindow class?
I mean something like:
<Window x:Class="WpfAnimationTEst.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
SpecialTo=200>
I know it can be done using attached dependency properties, but is it the only way? Is it not possible to call a dependency property defined in the code-behind?
Thank you and sorry if the question is some kind of stupid, i'm just learning and trying to understand WPF.
I found the answer after I initially posted a wrong answer:
The problem really lies in circular dependencies if you use andreask's answer. I had to create a BaseClass for all windows:
1) Create a new Window Base Class:
public class BaseWindow : Window {
public BaseWindow() { }
public static readonly DependencyProperty SpecialToProperty = DependencyProperty.Register("SpecialTo", typeof(double), typeof(BaseWindow));
public double SpecialTo {
get {
return (double)GetValue(SpecialToProperty);
}
set {
SetValue(SpecialToProperty, value);
}
}
}
This will be the new baseclass for all your windows.
2) Modify your MainWindow xaml: (Change YOURNAMESPACE (2x) to your namespace name)
<local:BaseWindow x:Class="YOURNAMESPACE.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:YOURNAMESPACE"
Title="MainWindow" Height="350" Width="525" SpecialTo="100">
<Grid>
</Grid>
</local:BaseWindow>
3) And you also need to modify your partial MainWindow.cs:
public partial class MainWindow : BaseWindow {
public MainWindow() {
InitializeComponent();
}
}
That worked for me, however, you will always need to use the extra xaml markup in your window declaration.
I'm answering my own question because there seems to be many ways to solve it correctly. I've upvoted the answers that best helped me, but i can't set any as the correct answer since all are correct.
So i'll just post a conclusion. If you think that i'm mistaken, please post a comment and i will correct my mind.
The main answer to my question is no, it is not possible to directly call a custom dependency property defined at code-behind from its "linked" XAML file. It is mandatory to instantiate the control in which the property is defined to call it.
To me, the best workarrounds to use a custom dependency property in XAML, defined in the code-behind are the posted by #Clemens and #Noel Widmer. This and this
You can use custom dependency properties in XAML, but only if you instantiate the control in XAML. For example, take a customized TextBox element:
public class MyTextBox : TextBox
{
public static readonly DependencyProperty SpecialToProperty = DependencyProperty.Register("SpecialTo", typeof(double), typeof(MyTextBox));
public double SpecialTo
{
get
{
return (double)GetValue(SpecialToProperty);
}
set
{
SetValue(DoubleAnimation.ToProperty, value);
}
}
}
You can of course create an instance of MyTextBox in XAML and assign the SpecialTo property there:
<custom:MyTextBox SpecialTo="1.0" />
In your case, however, you're not instantiating the custom class MainWindow, but you create a new instance of class Window, and the Window class isn't aware of the custom dependency property (the SpecialTo property is not even available in Window, since you declared it within the MainWindow class).
For the dependency property to be recognized, you'd need to instantiate MainWindow directly:
<custom:MainWindow
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
SpecialTo=200>
However, this means you need to omit the x:class directive that used to combine XAML and codebehind of your window (otherwise you'd run into circular dependencies), and I'm not sure if this correctly initalizes your window...
Yes, it is possible. Dependency properties are used to bind within XAML. If you want to bind to property defined in the code behind window you need to reference this window as XAML element, i.e. add tag for your main window x:Name="mainWindow", and next in the binding expression refer it as ElementName=mainWindow

Add member method as a resource

I'm implementing a class that contains an ObservableCollection and in my XAML I have a polyline.
I successfully binded the XAML dataContext to the this class and the polyline to the Observable collection. But now, of course, I'm facing a wrong type conversion.
I found an example of value converter and I added it to my code but I'm not able to add it as a resource in my XAML ...
The overall structure looks like that
public class externalClass
{
public ObservableCollection<Point> debugCh1 { get; set; }
public void test()
{
... performo modifications
on debugCh1 for testing purposes...
}
public class PointCollectionConverter : IValueConverter
{
.. implements convert and cnverBack
}
}
For the XAML
<Window x:Class="tester.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="277" Width="525" xmlns:my="clr-namespace:binding;assembly=binding" xmlns:my1="clr-namespace:deviceManager;assembly=deviceManager" Closing="Window_Closing">
<Window.Resources>
<local:PointCollectionConverter x:Key="pointCollectionConverter"/>
</Window.Resources>
... The window Itself ...
<Polyline Points="{Binding debugCh1}" />
...
</Window>
And for the C# behind
public partial class MainWindow : Window
{
private externalClass toTest;
public MainWindow()
{
InitializeComponent();
DataContext = toTest;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
toTest.test();
}
}
The whole thing works nice but for the <local:PointCollectionConverter..
Compiler says The type 'local:PointCollectionConverter' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built.
Any suggestions on how to add this reference??
You just have to make sure the namespaces are lined up. I'd start by separating your converter class from the externalClass class (I'm not sure it's even possible to reference nested-classes like that from XAML):
namespace MyCompany.MyProject
{
public class PointCollectionConverter : IValueConverter
{
.. implements convert and cnverBack
}
}
Now you can define the local xmlns and link it to MyCompany.MyProject:
<Window xmlns:local="clr-namespace:MyCompany.MyProject"
And with that the converter should be accessible as written.
<local:PointCollectionConverter x:Key="pointCollectionConverter"/>

WindowsFormsHost steals focus on activating application even activating by application's other wpf form

To Reproduce my case (.net 4.0)
Create a WPF Application (MainWindow.xaml)
Add a Winform user control that contains a textbox (UserConrol1.cs - Winform)
Put UserControl1 into MainWindow.xaml with windowsformshost
Add another WPF Window that contains a textbox(wpf) to project (Window1.xaml)
Create and Show Window1 after MainWindow InitializeComponent
Your project is ready,
Run Project and set textbox focused in MainWindow.xaml (that in WindowsFormsHost)
Deactivate your application by opening a window (Windows file explorer ,notepad, winamp etc.)
Try to write in textbox that in Window1 window by clicking textbox with mouse
And you will see that you can't set focus on textbox in Window1 because MainWindow Texbox( in winformshost will steal your focus on you application got activating)
Any idea?
MainWindow.xaml
<Window x:Class="WinFormsHostFocusProblem.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WinFormsHostFocusProblem"
xmlns:my="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
Title="MainWindow" Height="350" Width="525">
<Grid>
<my:WindowsFormsHost Focusable="False" >
<local:UserControl1>
</local:UserControl1>
</my:WindowsFormsHost>
</Grid>
</Window>
MainWindow.xaml.cs
namespace WinFormsHostFocusProblem
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Window1 window1 = new Window1();
window1.Show();
}
}
}
Window1.xaml
<Window x:Class="WinFormsHostFocusProblem.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WinFormsHostFocusProblem"
xmlns:my="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
SizeToContent="WidthAndHeight"
ResizeMode="NoResize"
Topmost="True"
Title="Window1" Height="300" Width="300" Background="Red">
<Grid>
<TextBox Height="25">asd</TextBox>
</Grid>
</Window>
Window1.xaml.cs
namespace WinFormsHostFocusProblem
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
}
}
I used my MSDN support contract to get an answer to this problem. The engineer was able to repro from yunusayd's sample and confirmed it is almost certainly a bug in WindowsFormsHost.
Thanks to yunus for the minimal repro sample and Keith at Microsoft for tackling the issue and providing a workaround in less than one day.
Workaround code follows. It works by using .NET reflection to change a private variable used in WindowsFormsHost and disable the trigger for the bug. According to the engineer I worked with, this relies on WPF internals, but he spoke with product team members and it should be safe to use. There's no guarantee of lack of side effects, of course, but so far I haven't found any problems in my testing with multiple WindowsFormsHosts in multiple WPF windows (maybe nesting would be trickier). I modified the original workaround to work generically with multiple windows. You can just as easily hardcode references to specific windows and named WindowsFormsHost controls in the Application_Deactivated event and skip the whole "LastActive" scheme and extension methods.
// App.xaml.cs: you must hook up to Application.Deactivated
void Application_Deactivated(object sender, EventArgs e)
{
foreach (Window w in windows)
{
foreach (var host in UI.DependencyObjectExtension.AllLogicalChildren(w).
Where(c => c is WindowsFormsHost))
{
FIELD_FOCUSED_CHILD.SetValue(host, null);
}
}
}
public readonly static FieldInfo FIELD_FOCUSED_CHILD = typeof(System.Windows.Forms.Integration.WindowsFormsHost).
GetField("_focusedChild", BindingFlags.NonPublic | BindingFlags.Instance);
public static class DependencyObjectExtension
{
/// <summary>
/// Returns a collection of o's logical children, recursively.
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
public static IEnumerable<DependencyObject> AllLogicalChildren(this DependencyObject o)
{
foreach (var child in LogicalTreeHelper.GetChildren(o))
{
if (child is DependencyObject)
{
yield return (DependencyObject)child;
if (child is DependencyObject)
{
foreach (var innerChild in AllLogicalChildren((DependencyObject)child))
{
yield return innerChild;
}
}
}
}
}
}
We had a similar problem in one of our applications and found that upgrading to .net 4.5 seems to have fixed a good portion of our application's WPF/WinForms focus issues including a similar one to this.
In addition, the _focusedChild field no longer exists in the .net 4.5 version of WindowsFormsHost

Expose UserControl property to XAML

WPF controls have certain properties (UserControl.Resources, UserControl.CommandBindings) that can have items added to them from the XAML of a user control declaration. Example:
<UserControl ... >
<UserControl.CommandBindings>
...
</UserControl.CommandBindings>
<UserControl.Resources>
...
</UserControl.Resources>
</UserControl>
I have a new list property defined in my user control:
public partial class ArchetypeControl : UserControl {
...
public List<Object> UICommands { get; set; }
I want to add items to this list like I can with resources and CommandBindings, but when I do this:
<c:ArchetypeControl.UICommands>
</c:ArchetypeControl.UICommands>
I get the error "Error 4 The attachable property 'UICommands' was not found in type 'ArchetypeControl'. "
Suggestions?
-
Given the comments, I've created a test control to show the entire code and reproduce the problem. I'm using visual studio 2010.
<UserControl x:Class="ArchetypesUI.TestControl"
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:c="clr-namespace:ArchetypesUI"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<c:TestControl.TestObject>
</c:TestControl.TestObject>
<Grid>
</Grid>
</UserControl>
-
namespace ArchetypesUI
{
/// <summary>
/// Interaction logic for TestControl.xaml
/// </summary>
public partial class TestControl : UserControl
{
public Object TestObject { get; set; }
public TestControl()
{
InitializeComponent();
}
}
}
Now the error I get is "Error 2 The attached property 'TestControl.TestObject' is not defined on 'UserControl' or one of its base classes."
Take a look at your XAML:
<UserControl>
^^^^^^^^^^^
<c:TestControl.TestObject>
^^^^^^^^^^^
</c:TestControl.TestObject>
</UserControl>
Here, you are declaring a UserControl, and then trying to set a TestControl property on it. Since UserControl doesn't have the TestControl.TestObject property, WPF that it can't set that property on the UserControl object. You may say, "But I'm declaring a UserControl of type TestControl. My UserControl is a TestControl!" But that's not quite the case. The above declaration is declaring the TestControl class: it's not creating an instance of TestControl, so it can't have instance properties set on it.
Rather, the TestObject property is there for users of TestControl to set on individual instances of TestControl:
<local:TestControl>
<local:TestControl.TestObject> <!-- Now it will work -->
</local:TestControl.TestObject>
</local:TestControl>
If you want to set a default / initial value for the TestObject property, then you can do so either in the TestControl constructor, or (if TestObject is a dependency property) through the TestControl default style (though this is more for custom controls than for user controls).
I'm not quite able to recreate your issue... the case I've created seems to work. I did have to initialize the list in the constructor.
However, from your example I wonder a more appropriate place for your list source would be on a ViewModel object of some sort. If you're exposing commands, having an IEnumerable of some sort of a ICommand wrapper which also encapsulates the display elements you need (e.g. Caption, Icon URI, etc).
ViewModels are certainly not a panacea, but in this case I think it would let you put all the knowledge of the commands you want to use in the same place (e.g. which are available and what they do).

Resources