I add a TextBlock to the MainWindow in XAML. And I would need to change the TextBlock Text in a separate class resided in a separate .cs file. I tried the following:
private static fooNameSpace.MainWindow tW1;
tW1 = this;
tW1.textBlock1.Text = "This is a paragraph";
It worked if the class is reside in the same file as the MainWindow class, But it throws me an null exception if the class is reside in a separate file. I have already added the using fooNameSpace; Still doesn't work
I can't figure out the right way to make a reference from a separate file class to the MainWindow and it's Control. Tips anyone?
thanks,
To answer my question - use internal instead of public.
// in MainWindow.xaml.cs internal
internal static fooNameSpace.MainWindow tW1;
// in foo.cs
MainWindow.tW1.txtBlock1.Text = "This is a paragraph";
the internal keyword allows other class in other cs file to get access to MainWindow controls.
But I'm not so sure about using internal to solve this problem as it allow my other class to get access to everything else in my MainWindow...any better option out there?
You mentioned XAML, so I will assume you are talking about a WPF application. the .xaml and .xaml.cs files go hand in hand. If you need to access anything in that "control" you will need to instantiate it or need its reference in the outside class.
As for the error, you declare the tw1 but it is not instantiated - which is the reason you are getting a Null exception error. Doing tw1 = this is also won't work.
Related
I'm trying to convert this WPF application to WPF UserControl so I could use it in WinForms application via ElementHost. I'm new to WPF and have never even touched it prior to this attempt so I might be going about it completely the wrong way.
I got the UserControl project to compile, however, my StaticResources get underlined in VS with message "The resource 'x' could not be resolved". I've tried moving the xamls with the needed x:Key elements up one level (the same level as the UserControl Dijagram.xaml), but it still cannot resolve them.
In the WinForms app, when trying to add the UserControl through designer by selecting hosted content in ElementHost tasks I get the following error:
An error occured trying to create an object of type
'DijagramLC.Dijagram'. Make sure the type has a default constructor.
(even though default constructor exists).
However, if I add it in codebehind, like this:
wpfUserControl = new Dijagram();
elementHost1.Child = wpfUserControl;
Controls.Add(elementHost1);
the code compiles but throws this runtime error: "System.Windows.Markup.XamlParseException: 'Provide value on 'System.Windows.StaticResourceExtension' threw an exception.' Line number '20' and line position '4'. ---> System.Exception: Cannot find resource named 'MyToolbar'. Resource names are case sensitive."
I've tried with and without App.xaml and adding ResourceDictionary elements for problematic xamls, but basically, I have no idea what I'm doing :)
I've uploaded the code to my SkyDrive and would really appreciate it if someone could take a look and tell me what I'm doing wrong:
https://skydrive.live.com/redir.aspx?cid=21be1f8e850e85cc&resid=21BE1F8E850E85CC!353
I hate jumping in blindly to new techonoly like this, but I have had no choice this time, and need to know if my requirement is even achievable this way.
You are probably getting the error because you use resources from a resource dictionary which is not loaded. Loading a resource dictionary in the hosting application will probably solve the issue:
// When hosting a WPF usercontrol inside an element host,
// application resources are not loaded, so we need to load them manually.
var resources = new ResourceDictionary
{
Source = new Uri("/UNIT4.MKB.GUI.XAML.Dashboard.Resources;component/resources.xaml", UriKind.Relative)
};
// Check for null reference
if (Application.Current != null)
{
//Merge the loaded ResourceDictornairy with the dummy application Resources.
Application.Current.Resources.MergedDictionaries.Add(resources);
}
The problem is, you need THE default constructor like this:
public CreatedPollsUC()
{
InitializeComponent();
}
If you have any other code in the constructor, the error occures:
public CreatedPollsUC()
{
InitializeComponent();
// ... more code
}
So if you want to use further code in the constructor, you need to apply the control first to the element host. Then you can edit the constructor.
Why do I have this error message for a UserControl:
Partial declaration of
MyNamespace.MyUserControl must not
specify different base classes
Just because I inherited from another UserControl class I created in another namespace whereas this other namespace is referenced in the XAML as
xmlns:my="clr-namespace:ReferedNamespace;assembly=ReferedNamespace"
Little to go on here, but this usually happens when the code behind and the xaml file do not inherit from the same base class.
Since we do not have all the details concerning your problem,
I'll create a situation that will cause the same exception to be thrown,
this might help you understand your problem.
As an example, just create new WPF application using Visual Studio,
The XAML might look something like this:
<Window x:Class="WpfApplication1.MainWindow" .....>
The code behind would then contain something like this:
public partial class MainWindow : Window
{
//Code here
}
Note the 'partial' modifier here. It means this class (MainWindow) might
not be defined in a single file but spread out across multiple files,
in this case the XAML (.xaml.cs) and the CS (.cs) files.
Now add a new UserControl to the solution. It will be named UserControl1.
Without making any changes to the XAML, change the code behind for the MainWindow:
public partial class MainWindow : UserControl1
{
//Code here
}
Now you'll get the exception you questioned about.
Look for something like this in your code, if you still can't find a solution,
please provide more code.
look to both your .cs and .xaml files at this parts
in .xaml file :
<Window x:Class="BUSsAsDesign.GUI.IGPopUP" > ...... </Window>
in .cs file :
namespace BUSsAsDesign.GUI
{
public partial class IGPopUP : Window
{
//code here
}
}
Now if u wanna change Window to UserControl
change
<Window x:Class="BUSsAsDesign.GUI.IGPopUP" > ....... </Window>
<!--**becomes**-->
<UserControl x:Class="BUSsAsDesign.GUI.IGPopUP" > ....... </UserControl>
namespace BUSsAsDesign.GUI
{
public partial class IGPopUP : Window
{
//code here
}
}
//**becomes**
namespace BUSsAsDesign.GUI
{
public partial class IGPopUP : UserControl
{
//code here
}
}
- i hope it`s useful :) .
I wanted to add this piece of information. In Visual Studio 2017, There is a bug which I haven't had time to dig into with much depth, but it causes this error. (from the OP)
Overview: When declaring a partial class as an x:Class for a resource xaml file, it will cause this error, and after removing the declaration, the error will persist.
To reproduce this bug, (or if you are here because you are getting this error message)
Step 1: Create a new WPF Project.
Step 2: Create a new Resource File
Step 3: Change the resource files name-space to the projects main namespace (remove the bit at the end.)
Step 4: In the resource files declaration/header section, add an x:Class declaration specifying your MainWindow (default startup window object) as the Class for that resource file. (EG: x:Class=MainWindow)
Step 5: Clean/Rebuild Solution
Step 6: You should now be getting this error from the OP. So remove the x:Class Declaration from your header on the Resource File, and save/clean/rebuild the project.
If the bug was reproduced, the error should remain, even though you have removed the x:Class declaration from the resource file.
The only solution I could find for this bug, is to delete the projects Bin folder, and any other folder with builds in it.
After deleting them, Clean/Rebuild your project, and the error should be gone.
I have read multiple posts on the subject but still cannot manage to make it work.
I want 2 user controls slidertype1 and slidertype2 which should inherit from slidercommontype, all are in same namespacecommon, can someone knows the syntax for this simple use case ?
Inspiring from http://jamescrisp.org/2008/05/26/wpf-control-inheritance-with-generics/
I tried:
<namespacecommon:slidercommontype x:Class="namespacecommon.slidertype1">
but I got namespacecommon:slidercommontyp doesn't exist in xml namespace.
As long as the base class doesn't have a XAML file associated with it, it's pretty easy. Trying to incorporate the visual aspect of the user control using XAML is not really a supported scenario.
Having said that, just create your class SliderCommonType (although I would call it SliderBase or something.)
namespace MyControls {
public class SliderBase : UserControl {
}
}
Then create your two controls based on it. I'll show one example and the other should be obvious.
<Local:SliderBase x:Class="MyControls.SliderType1"
xmlns:Local="clr-namespace:MyControls">
</Local:SliderBase>
And the code-behind would look like this:
namespace MyControls {
public class SliderType1 : SliderBase {
}
}
The key point being that your XAML file has to reference the base class which requires changing the <UserControl> element to <Local:SliderBase> which in turn requires a XAML namespace import.
When you add a UserControl using the default template, you can just change the code it creates to reflect the above changes. It's much easier than trying to create it from scratch.
One last thing to note - you will need your application to compile successfully before you can use the visual designer on your derived controls. This is because the designer needs to be able to instantiate SliderBase at design-time.
I'm currently working on enabling drag-and-drop support for our company app.
The error I keep getting seems weird to me.
What this says is that
The property 'DragDropHelper.IsDragSource' does not exist in XML namespace 'clr-namespace:DragAndDrop;assembly=DragAndDrop'. Line 61 Position 83
The property is an attached property in the class I found in the Internet in the samples and modified it a bit. Here is property declaration:
namespace DragAndDrop {
public class DragDropHelper
{
public static readonly DependencyProperty IsDragSourceProperty =
DependencyProperty.RegisterAttached("IsDragSource", typeof (bool), typeof (DragDropHelper),
new UIPropertyMetadata(false, IsDragSourceChanged));
public static bool GetIsDragSource(DependencyObject obj)
{
return (bool) obj.GetValue(IsDragSourceProperty);
}
public static void SetIsDragSource(DependencyObject obj, bool value)
{
obj.SetValue(IsDragSourceProperty, value);
}
It seems to me that attached property is completely valid, isn't it?
This DragDropHelper is included into a class library, that I reference from the main client app.
When I try to set the value of the property in a client app:
<ListView x:Uid="list" x:Name="CurrentFolderItemsControl" drag:DragDropHelper.IsDragSource="true" />
VS2010 says that property doesn't exist in XML namespace. The XAML document is a resource dictionary
which is merged into main client app resources, because it contains styles for our control.
It's even more weird because I created a class within main app that has attached property, then set property value in XAML markup - app compiled OK
Sorry for the necro... just thought I'd share what happened in my similar scenario. I copied my View from an external project, which referenced the behaviour's namespace internally:
xmlns:b="clr-namespace:MyCompany.Common.Behaviours"
b:WindowBehaviours.Close="{Binding ClosingView}"
Two things needed to happen for this to work. Firstly, the xmlns needed to explicitly reference the assembly for the behaviour class, like so:
xmlns:b="clr-namespace:MyCompany.Common.Behaviours;assembly=Common"
Secondly, I temporarily removed the second line and rebuilt my solution first. VS2012 sometimes gets its knickers in a knot when you clone WPF projects, and a good Clean & Rebuild without the offending line often fixes things (it recognised the behaviour after I added the line back again).
Problem solved. My error was I didn't recompile the library after having added attached property. After I did so, everything works as expected. Sorry everybody :(
I had exactly the same problem as you did. I got it to work by placing the [AttachedPropertyBrowsableForChildren] attribute above my setter method. Don't ask me why, it just worked...
I got this error when I defined the control (button in my case) before defining the handler. I had to delete the button and redefine it after creating the method to clear the error.
I am using the NavigationFramework in Silverlight 3, and am running into issues where the constructor of the UserControl in the xaml I am loading is not being called, and I believe this is because the UserControl in the xaml I am calling is actually derived from another user control.
I have stepped through the debugger with specific break points and the constructor is being ignored completey.
I have MyWindowBlue which is of type uctrlBaseMyWindow.
The constructor for uctrlBaseMyWindow is being called when the xaml is 'navigated to' but the constructor for MyWindowBlue is being ignored.
This is not the case if I add the user control via markup directly.
Anyone else have this issue?
The code I am using to navigate to the MyWindowBlue is
this.MyContentFrame.Navigate(new Uri("/Controls/uctrlMyWindowBlue.xaml", UriKind.Relative));
Has anyone run into this or could offer any help?
Thanks
Found the error in my code.
This was due to an error in my XAML. I had moved the user control to a different folder, and so the c# code behind had a type of the same name in one location in the namespace, but the XAML markup had the type in a different location (the original folder), and so the partial class with the constructor was not linked to the type I was actually instantiating.
I fixed the type reference to point to the proper location in the namespace and now the partial class code behind is linked back up.