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.
Related
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.
I found out that F# 2.0 apparently doesn't support public static fields anymore, which makes impossible the standard way of implementing a DependencyProperty:
public static readonly FooProperty = DependencyProperty.Register(...); // in C#
I don't quite like one suggested work-around for F# which involves declaring the DependencyProperty as a static mutable val and then initializing it with a static do... (or however exactly it goes).
I've tried exposing a DependencyProperty as a public static property instead of as a public static field, which seems to work just fine in a WPF application (I've tried data binding and style setters on the property, both with success):
type XY() =
inherit Control()
static let fooProperty =
DependencyProperty.Register("Foo", typeof<string>, typeof<XY>)
static member public FooProperty with get () = fooProperty // see update below:
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // not required!
member public this.Foo with get (): string = this.GetValue(fooProperty) :?> string
and set (x: string) = this.SetValue(fooProperty, x)
Are there any notable drawbacks to publishing a dependency property as a property, instead of as a field? Because this code looks much cleaner to me than the suggested work-around.
Update #1: I just found that in the above code, FooProperty (the public read-only property) isn't even required. So one could drop the line I high-lighted in the above code example and things still work just fine. I'm now even more curious why people go to such lengths using mutable val etc. when it's apparently that simple? Am I missing something important?
Update #2: In a comment below, Robert Jeppesen provided a hyperlink to an MSDN page which mentions the following:
If you fail to follow this naming pattern [ie. Foo → FooProperty] , designers might not report your property correctly, and certain aspects of property system style application might not behave as expected.
I put Expression Blend 4 to the test and found that it doesn't seem to be affected at all when the public static FooProperty is completely missing.
Yes, it does make a difference whether you use a public static field or not. But maybe not a significant difference, depending on your needs. I will explain where WPF itself behaves differently, then mention a couple of other situations in which it might also be a problem.
Effect on XAML parsing if you use a static property instead of a static field
The only part of WPF itself that actually notices whether you used a static property or a static field is the XAML parser, and the only situation where it makes a difference is when the same property name is used at multiple levels. This is because the existence of a static field with matching name and ending in "Property" is used to disambiguate between identically-named DependencyProperties at multiple levels.
One place you'll see a difference is if you define your property using a public static property (or nothing at all) and the ancestor class has a DependencyProperty the same name using a public static field, the ancestor class's property will be used instead of yours.
For example, suppose create a Control that has a DependencyProperty named "Language". FrameworkElement already has a "Language" DependencyProperty, but as long as you follow the standard and use a public static field, that's ok: Your "Language" property will take precedence. But if you use a public static property instead, your XAML will end up setting the "FrameworkElement.Language" dependency property, not yours.
This could be a problem if, for example, a new version of WPF comes out that has a new dependency property defined on one of your base classes. For example, if you are using a "Depth" property you've defined using a static field, and NET Framework 5.0 defines a "Depth" property on "Visual", your application won't work on the new version of NET Framework.
Another scenario where this may make a difference is when the class hierarchy is changed. WPF tries to protect you from versioning issues in this case, but its protection goes away if you used a public static property instead of a public static field. The simplest scenario is that you wrote a library and people are using your property. If you used a public static field their compiled application will actually include your class name so there can be no mistake. But if you used a public static property (or nothing at all) their compiled application will reference it using their derived class name. So if the inheritance hierarchy changes or a new property is introduced in between, it could shadow your original property even in compiled code. For example, this could be an issue if:
YourControl is derived from ThirdPartyGrid
YourControl was written when ThirdPartyGrid didn't have a "Language" field, so the compiled code references FrameworkElement.Language
If the vendor of ThirdPartyGrid adds a "Language" dependency property it won't affect your application
But if FrameworkElement.Language had been defined as a public static property, the vendor's addition would break your application
There are some even more esoteric situations where it can make a difference.
Effects on designer tools
As far as I can tell, neither Visual Studio nor Expression Blend behave any differently if you define the property using a public static property instead of a field, or even if you leave it out entirely, except when they encounter the XAML parser behavior mentioned earlier.
But it should be noted that there are many XAML development environments out there, and since the pattern of using static fields is so firmly established, they may rely on this. So it is caveat emptor.
Effects on WPF itself other than XAML parsing
Except for the XAML parser, no part of WPF cares whether you have defined a public static property, field, or nothing at all. You can use your DependencyProperties exactly the same way in each case. However:
I know of no guarantee this will always be true, and
Third party code could easily rely on it
I am new to WPF and the below question may look silly for many, please pardon me.
How can I create a dependency property in app.xaml.cs?
Actually, I tried to created it. The below code,
public static DependencyProperty TempProperty =
DependencyProperty.Register("Temp", typeof(string), typeof(App));
public string Temp
{
get { return (string)GetValue(TempProperty); }
set { SetValue(TempProperty, value); }
}
throws the below compile time errors:
The name 'GetValue' does not exist in the current context
The name 'SetValue' does not exist in the current context
Can anybody help me in this?
Thank you!
DependencyProperties can only be created on DependencyObjects, and since Application (which your App class inherits from) doesn't implement it, you can't create a DependencyProperty directly on the App class.
I assume you want this property to support binding. If this is the case, you have two options:
Implement INotifyPropertyChanged in App.xaml.cs
Create a DependencyObject derived class with your properties on it, and expose it as a standard read-only property of your App. The properties can then be successfully bound by "dotting-down" to them.
i.e if your new property is called Properties, you can bind like so:
<TextBlock Text="{Binding Properties.Temp}" />
If the property needs to be the target of a Binding, then option #2 is your best bet.
You class that contains dependency properties must inherit from DependencyObject.
I've run into an odd problem with attached properties where when I assign the property name in the call to RegisterAttached and name properly for the name of the attached property (say TranslateProperty and "Translate") the code for the attached property implementation doesn't fire. Just doesn't get called. If I change the string name to anything other than Translate (say "Translate_") the code gets called just fine.
Here's the implementation:
public class TranslateExtension : DependencyObject
{
public static readonly DependencyProperty TranslateProperty =
DependencyProperty.RegisterAttached("Translate_",
typeof(bool),
typeof(TranslateExtension),
new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender));
public static void SetTranslate(UIElement element, bool value)
{
AssignKeys(element);
element.SetValue(TranslateProperty, value);
}
public static bool GetTranslate(UIElement element)
{
return (bool)element.GetValue(TranslateProperty);
}
public bool Translate
{
set { base.SetValue( TranslateProperty, value); }
}
...
}
The above actually works because the property in the string is Translate_. If I change the string value to "Translate" it failed.
I have 2 other attached properties in the same class and they exhibit exactly the same behavior - same name as the AttachedProperty and they don't get called. Name it something else and it works.
I'm not sure what's going on here. My code is actually working with the invalid names, but I don't understand why, and more importantly I'm not sure if this wrong naming causes any side effects.
Can anybody see whether I'm overlooking something painfully obvious? I've revisited a few examples in articles of AttachedProperties and I don't see those implementations using special names - they always name the string property the same as the attached properties.
You shouldn't put extra code in your SetTranslate since it won't get called. From MSDN here:
Implications for Custom 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.
Instead, add a PropertyChangedCallback to your FrameworkPropertyMetadata.
I'm trying to create a UserControl that inherits from a generic class. It does not directly inherit from a generic class, but through an intermediate class that does not use generics. This compiles and works at runtime, but I get an error at design time.
Here's my generic parent class:
Public Class GenericParent(Of T)
Inherits UserControl
End Class
Here's my non-generic parent class:
Public Class NonGenericParent
Inherits GenericParent(Of String)
End Class
Here's my XAML:
<local:NonGenericParent x:Class="SilverlightApplication5.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SilverlightApplication5"
Width="400" Height="300">
<StackPanel>
<Button Content="Hello"/>
</StackPanel>
</local:NonGenericParent>
The IntelliSense parser gives the following errors:
The property 'Width' was not found in type 'NonGenericParent'.
The property 'Height' was not found in type 'NonGenericParent'.
The type 'NonGenericParent' does not support direct content.
It is as though IntelliSense can't see up the inheritance tree past the GenericParent class. I've tried specifying the ContentPropertyAttribute directly on the SilverlightApplication5.Page class, the NonGenericParent class, and it does not work.
I've read that the TypeArguments attribute is not supported in Silverlight 2.0. That is why I've created the intermediate NonGenericParent class.
If anybody has any ideas how to silence these errors I'd be eager to hear them.
Update: We've opened a support ticket with MSFT, I'll update this with whatever their solution is.
We've received word from Microsoft that this is not likely to be fixed in future versions. After they bounced the problem around trying to find the responsible group, it appears that this problem belongs to their WPF developer group, which is where the 'not going to fix it' answer came from.
In the meantime, we've updated our code to yank out the generics from the parent classes until I guess XAML 2009.
Not sure about silverlight, but this compiles and runs as expected in c#:
class GenericObject[T] : UserControl
{
}
class StaticObject : GenericObject[Int32]
{
public Int32 wide { get { return this.Width; } }
}
private void Form1_Load(object sender, EventArgs e)
{
StaticObject so = new StaticObject();
this.Text = so.wide.ToString();
}
So if it compiles against the clr, it should work just fine.
Could be just an intellisense bug as you're suggesting. Normally I'd advise against ignoring comiler warnings, but in this case it seems that the warning is not valid.
edit: substituted angle brackets with square brackets cause SO stripped them.
Despite being at 2.0 silverlight (and especially the VS2008 tweaks for silverlight) are still very young. There are still quirks in the IDE stuff.
Do you still have the problem even after a sucessful build?
This blog post seems to be related to your issue:
http://blogs.msdn.com/b/wpfsldesigner/archive/2010/01/22/known-issue-controls-deriving-from-a-generic-base-class-must-be-in-separate-assembly.aspx
For Silverlight it seems that you must have 3 classes for this to work.