UserControl that has a generic class in its inheritance tree - silverlight

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.

Related

How does this type of static XAML Binding work?

I cam across the following code in a XAML document, and I do not understand the syntax, nor do I understand how it is supposed to work.
The XAML contains the following Binding (or I guess it's some sort of Binding):
<Button Content="Export all" Command="{atf:CommandService {x:Static MyProgramme:ExportCommands+Commands.ExportAll}}">
In this project, there is a class indeed called CommandService (which is quite large so I can't share the full code, but see the ATF framework), and another class:
public class ExportCommands
{
private enum Commands
{
ExportAll
}
}
I do no understand the syntax of the XAML expression. How does it relate the CommandService class to the actual command? Are there similar examples that use this syntax?
The ATF CommandService is a custom MarkupExtension provided by the framework. An example of a mark up extension can be found here

wpf DataContext error in Designer

I have a presentation involving (3) DataGrids that are almost the same, but different enough that it seems like a cleaner design to do just the whole thing in code.
It is still raw (class diagram below), but works the way I want except for one thing! The visual studio designer can't figure out the late binding of the DataContext, so it throws an error.
An example of how I am pulling the grid's data context for use in a given column is below, as well as the error I get.
Does s anyone see a way to make the designer happy with the existing code?
Does anyone have a suggestion for a better approach?
I know there are ways to give Blend some notion of data but I don't as yet know Blend.
Cheers,
Berryl
CODE
public abstract class TimesheetGridColumn : DataGridTextColumn
{
...
protected ActivityCollectionViewModel _GetDataContext() { return (ActivityCollectionViewModel) DataGridOwner.DataContext; }
public virtual void SetHeader() {
var tb = new TextBlock
{
Text = _GetHeaderText(),
ToolTip = _GetHeaderToolTip(),
};
Header = tb;
}
....
}
public class ActivityDescriptionColumn : TimesheetGridColumn
{
...
*** WORKS at RUNTIME but DESIGNER does not know that *******
protected override string _GetHeaderText() {
return _GetDataContext().PresentationSubject;
}
}
XAML SNIPPET & DESIGNER ERROR
<Expander Header="{Binding DisplayName}" BorderThickness="1" IsExpanded="True">
<dataGrid:ActivityDataGrid /> <=============== simple but error
</Expander>
System.NullReferenceException
Object reference not set to an instance of an object.
at ...ColumnSubclasses.ActivityDescriptionColumn._GetHeaderText() in ActivityDescriptionColumn.cs:line 24
CLASS DIAGRAM
If all you need is to get the designer to work again, you can probably put a DesignerProperties.GetIsInDesignModecheck in somewhere.
How about:
protected override string _GetHeaderText()
{
if (!DesignerProperties.GetIsInDesignMode(this))
{
return _GetDataContext().PresentationSubject;
}
else
{
return "Design Mode Text";
}
}
You may be able to solve your designer problem with the Designer Attributes that are a part of WPF. Follow this link to an MSDN article on Design-time attributes and look specifically at the d:DataContext attribute. If you can create a sample implementation of the class that your grids are binding to, you may be able to get the designer working for you again.

The property does not exist in XML namespace

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.

How to properly use a Subclassed silverlight control?

I created this class where I wanted to override this specific event for the content control.
public class MyContentControl : ContentControl
{
protected override void OnKeyUp(KeyEventArgs e)
{
//do something
//..........
e.Handled = true;
}
}
However when I am using this control in my XAML everything compiles and works fine, but I am getting a runtime exception and I am not sure exactly why? Could someone point me in the right directions....
The exception I get is
XamlParseException
UPDATED (Shows where abouts of the exceptions)
In the XAML I have:
xmlns:ctrls="clr-namespace:SilverlightProject.CustomControls"
and I use it like:
<ctrls:MyContentControl Grid.Column="0" x:Name="_contentControl" VerticalAlignment="Center" HorizontalAlignment="Center" />
Content controls require a default template to be created somewhere (e.g. in generic.xaml). They do not have a matching XAML file like user controls.
If you can provide more information, I can show you how to create an appropriate template.
There are many reasons for this.
To start with. Give the fully qualified namespace.
Instead of
xmlns:ctrls="clr-namespace:SilverlightProject.CustomControls"
Use
xmlns:ctrls="clr-namespace:SilverlightProject.CustomControls;assembly=YourAssebmlyName"
If that, doesn't help.
You directly attach your control with the application. Then, enable Debug -> Exceptions. Check Thrown option for the CLR execetion checkbox. You have fair amount of possibility to get to know the cause.

Silverlight 4 Equivalent to WPF "x:static"

I'm working on a project that is based on an old project someone started and didn't finish. I was trying to use as much of their code as I could, so in doing so I ran into some tweaking issues.
Namely, when I put some of the old xaml in the new project there were some errors that were thrown regarding the "x:static" property and "Dynamic property."
here are the error messages themselves:
Error 1: The type 'DynamicResource' was not
found. Verify that you are not missing
an assembly reference and that all
referenced assemblies have been built.
Error 2: The type 'x:Static' was not found.
Verify that you are not missing an
assembly reference and that all
referenced assemblies have been built.
Some notable points that I think is causing the errors: the old project was programmed in VS2008, WPF, v3.5 .Net framework; whereas I am programming in VS2010, Silverlight 4, .Net framework v4.0.
I realize there are differences from WPF to Silverlight as far as xaml goes and there are plenty of differences from the different .Net framework versions and editions of Visual Studio. But I just can't seem to find a fix for this anywhere so I didn't know if there was just a library I was missing or just something I'm simply overlooking or what.
I can recreate this if need be, but like I said, I'd rather use as much of the old code as I can as long as the tweaking doesn't cause more trouble than what it's worth.
Unfortunately, you can't directly use the DynamicResource and Static keywords in a Silverlight's subset of XAML, but you can mimic their behavior. Here is the article on the topic:
{x:Type} and {x:Static} in Silverlight
In general, there is no easy way to migrate a project from WPF to Silverlight. They have very much in common, but strictly speaking are a different technologies.
Another way to achieve binding to static properties - to bind in code. Below is an example.
Main application class:
public partial class App : Application
{
public static MyViewModel MyViewModel { get; private set; }
// ...
}
Main window markup:
<TextBlock Loaded="MyTextBlockLoaded" />
Main window back-code:
public partial class MainPage : PhoneApplicationPage
{
// ...
private void MyTextBlockLoaded(object sender, RoutedEventArgs e)
{
TextBlock textBlock = ((TextBlock)sender);
if (textBlock.Tag == null)
{
textBlock.Tag = true;
Binding bind = new Binding("MyInfo");
bind.Source = App.MyViewModel;
bind.Mode = BindingMode.OneWay;
textBlock.SetBinding(TextBlock.TextProperty, bind);
}
}
}
Maybe the TextBlock.Tag approach of checking, was Binding already set or not, isn't the most elegant one, but it works.

Resources