Show hidden WPF elements in Visual Studio designer - wpf

As opposed to this, does anybody has figured out a way to show all hidden elements while working in Visual Studio designer(or Blend)?
It's anti-productive to constantly change the default visibility property of elements to be able to see them while editing Xaml files.

After researching, I found this. So here's a tested solution that can be implemented in the view model :
//Declare default Visibility values
private Visibility _processBarVisibility = Visibility.Hidden;
private Visibility _buttonVisibility = Visibility.Hidden;
public ViewModel()
{
//In constructor, override Visibility values if in design mode
DependencyObject dep = new DependencyObject();
if (DesignerProperties.GetIsInDesignMode(dep))
{
_processBarVisibility = Visibility.Visible;
_buttonVisibility = Visibility.Visible;
}
}

Related

Creating property for WPF user control datagrid

I have a user control with a datagrid called IGrid. I want to add GridViewColumnCollection poperty for it.
public class DataGridNumericColumn : DataGridTextColumn
{
protected override object PrepareCellForEdit(System.Windows.FrameworkElement editingElement, System.Windows.RoutedEventArgs editingEventArgs)
{
TextBox edit = editingElement as TextBox;
edit.PreviewTextInput += OnPreviewTextInput;
return base.PrepareCellForEdit(editingElement, editingEventArgs);
}
void OnPreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
{
try
{
Convert.ToInt32(e.Text);
}
catch
{
e.Handled = true;
}
}
}
From Google i got a piece of code `
private Collection<DataGridColumn> field = new Collection<DataGridColumn>();
[Category("Data")]
[Description("Column Creation")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public Collection<DataGridColumn> Columns
{
get { return field; }
}
Here I can get GridViewColumnCollection in visual tree ,
My question is how to add a new type (DataGridNumericColumn )in the collection using the above code.
If you do not know what the code does, it is probably best to research it before attempting to use it or come up with your own solution. As far as I can tell, you are attempting to add an additional property to a UserControl that inherits DataGrid.
You have two options:
Create a DependencyProperty (the best choice, in my opinion).
Create a normal property
Here's a couple links to help you get started:
What is the difference between Property and Dependency Property
When should I use dependency properties in WPF?

Custom Usercontrol with MVVM and Catel

I've created a custom usercontrol that's composed of a AutoCompleteBox with a Selected Item... till now I've implemented it in a way I don't like... I mean I've a XAML view, a Viewmodel and in the viewmodel I load data from a stored procedure.
Since the AutoComplete box is a third party UserControl I've added it to the XAML view and not defined as a custom usercontrol. What's the best practice to do so?
I think the fact that I'm using Catel as MVVM Framework is irrilevant right now..
Thanks
UPDATE #1
My usercontrols need to have some properties that are passed via XAML for example (LoadDefaultValue)
<views:PortfolioChooserView x:Name="PortfolioChooserView" DataContext="{Binding Model.PortfolioModel}" Height="25" LoadDefaultValue="True" Width="150" />
To achieve such a scenario I had to define a dependency property in my PortfolioChooserView defined as
public bool LoadDefaultValue
{
get { return (bool)GetValue(LoadDefaultValueProperty); }
set { SetValue(LoadDefaultValueProperty, value); }
}
public static readonly DependencyProperty LoadDefaultValueProperty = DependencyProperty.Register(
"LoadDefaultValue", typeof(bool), typeof(PortfolioChooserView), new PropertyMetadata(default(bool)));
Since if I would have defined it in Viewmodel only I wouldn't have been able to set it.
The odd thing is that in order to pass it to the viewmodel I had to do such a trick
public PortfolioChooserView()
{
InitializeComponent();
if (!isFirstLoad) return;
Focusable = true;
PortfolioCompleteBox.AllowDrop = true;
PortfolioCompleteBox.Focus();
DragDropManager.AddPreviewDragOverHandler(PortfolioCompleteBox, OnElementDragOver);
DragDropManager.AddDropHandler(PortfolioCompleteBox, OnElementDrop);
DataContextChanged += PortfolioChooserView_DataContextChanged;
isFirstLoad = false;
}
void PortfolioChooserView_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
var dataContext = DataContext as PortfolioModel;
if (dataContext != null)
{
dataContext.LoadDefaultValue = LoadDefaultValue;
dataContext.AllowNull = AllowNull;
//var converter = new PortfolioConverter();
//var portfolio = (Portfolio) converter.Convert(SelectedItem, null, null, CultureInfo.CurrentCulture);
//dataContext.SelectedItem = portfolio;
}
}
But I really dislike to use the DataContextChanged event ...do you see a better approach?
Thank
UPDATE#2
I keep this toghether since It's a related question...
On some viewmodel I used DeferValidationUntilFirstSaveCall = true; in the Constructor to disable the validation at load but my custom usercontrols shows the red border around... what should I do to propagate that info to the nested usercontrols?
Thanks again
See Orc.Controls for tons of examples. It's an open-source library that has a lot of user controls built with Catel, even one with an auto complete box.

WPF Override Metadata Foreground Dependency Property

I'm hoping someone can shed some light on my problem as I've searched everywhere and can't find an explanation or solution to this.
To explain the problem I have created a class called Label which inherits from TextBlock and I want to override the default Foreground brush, Font Weight, Font Size and Font Family; all the overrides work apart from the Foreground (I can override the background without a problem so it is something specific to the foreground property).
Create a new WPF application and create this simple class: -
namespace WpfApplication
{
public class Label : TextBlock
{
static Label()
{
ForegroundProperty.OverrideMetadata(typeof(Label), new FrameworkPropertyMetadata(Brushes.Red));
FontWeightProperty.OverrideMetadata(typeof(Label), new FrameworkPropertyMetadata(FontWeights.Bold));
FontSizeProperty.OverrideMetadata(typeof(Label), new FrameworkPropertyMetadata(50.0));
FontFamilyProperty.OverrideMetadata(typeof(Label), new FrameworkPropertyMetadata(new FontFamily("Calibri")));
}
}
}
Create an instance of this new Label class in MainWindow.xaml: -
<Grid>
<local:Label Text="TEST" />
</Grid>
You should see that the Label doesn't adopt the new Foreground default but looking in SNOOP it is still inheriting it's value.
As far as I'm aware any Dependency Property can be overridden so any help would be much appreciated!
ForegroundProperty.OverrideMetadata(typeof(LcdTextBlock), new FrameworkPropertyMetadata(new SolidColorBrush(Colors.Lime)) { Inherits = false });
This works for me.
One workaround is:
public class Label : TextBlock
{
static Label()
{
ForegroundProperty.OverrideMetadata(typeof(Label), new FrameworkPropertyMetadata(Brushes.Red, OnForegroundChanged));
FontWeightProperty.OverrideMetadata(typeof(Label), new FrameworkPropertyMetadata(FontWeights.Bold));
FontSizeProperty.OverrideMetadata(typeof(Label), new FrameworkPropertyMetadata(50.0));
FontFamilyProperty.OverrideMetadata(typeof(Label), new FrameworkPropertyMetadata(new FontFamily("Calibri")));
}
private static void OnForegroundChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
MethodInfo mi = typeof(DependencyPropertyChangedEventArgs).GetMethod("get_OperationType",
BindingFlags.NonPublic |
BindingFlags.Instance);
var v = mi.Invoke(e, null);
if ((e.NewValue != Brushes.Red) && (v.ToString() == "Inherit"))
{
((Label)d).Foreground = Brushes.Red;
}
else
{
((Label)d).Foreground = (Brush)e.NewValue;
}
}
}
On VisualStudio 2012 in the design view the preview of you code show the text in red color. Something change it at runtime. But at the moment I can't tell you who and why... The dafault inherited value prevales!
Edit: here some good info.

Silverlight button on mainpage, linked to command, never calling the method

I'm brand new to Silverlight and I'm in the deep end a little over my head so I'm probably missing something really obvious. I'm working on an image editor and I have a button on my main page that is supposed to rotate images or text on my canvas. The button however isn't calling my rotate method. EDIT: It is now.
Here's all the code I've written related to the button
MainPage.xaml
<Button Command="{Binding Path=Project.RotateCWElementCommand}"..../>
Project.cs -
#region properties
public ICommand RotateCWElementCommand { get; set; }
#endregion
#region methods
public Project(int siteID)
{
this.RotateCWElementCommand = new DelegateCommand(RotateCWElement, CanRotateCWElement);
}
private void RotateCWElement(object param)
{
FrameworkElement element = this.SelectedElement;
RotateTransform cwRot = new RotateTransform();
cwRot.Angle = 90;
cwRot.CenterX = element.ActualWidth * 0.5;
cwRot.CenterY = element.ActualHeight * 0.5;
element.RenderTransform = cwRot;
}
#end region
#region Command conditions
private bool CanRotateCWElement(object param)
{
return true;
}
#endregion
The problem now is that it will only rotate once and some image quality also appears to be lost. The images move strangely when I click and drag them, and sometimes when I click the full image quality returns.
If anybody has any ideas about this it'd be great.
It sounds like the Button.DataContext does not contain a property called Project.RotateCWElementCommand
Verify that your Button's DataContext has a property called Project, and that Project has a property called RotateCWElementCommand
The output window in Visual Studio can be very helpful for finding issues with your bindings in Silverlight and will help clarify if Rachel's suggestion is the problem.

How to disable custom window rendering in WPF designer?

I have created window derived class (WindowAttachedCollection.MyWindow) and attached property which holds collection of these windows. But WPF designer in VS 2010 tries to create WindowInstance object for each window in that collection and it throws ArgumentException:
The value "Microsoft.Expression.Platform.WPF.InstanceBuilders.WindowInstance" is not of type "WindowAttachedCollection.MyWindow" and cannot be used in this generic collection.
Parameter name: value
So it breaks WPF designer.
Is there any way how to disable instancing WindowInstance instead of MyWindow in WPF designer? At this time I don't require any design-time support for this collection of MyWindow.
EDIT:
public static readonly DependencyPropertyKey DialogsPropertyKey = DependencyProperty.RegisterAttachedReadOnly(
"DialogsInternal",
typeof(ObservableCollection<MyWindow>),
typeof(MyWindow),
new PropertyMetadata(null));
public static readonly DependencyProperty DialogsProperty = DialogsPropertyKey.DependencyProperty;
public static void SetDialogs(UIElement element, ObservableCollection<MyWindow> value)
{
element.SetValue(DialogsPropertyKey, value);
}
public static ObservableCollection<MyWindow> GetDialogs(UIElement element)
{
var dialogs = (ObservableCollection<MyWindow>)element.GetValue(DialogsProperty);
if (dialogs == null)
{
dialogs = new ObservableCollection<MyWindow>();
SetDialogs(element, dialogs);
}
return dialogs;
}
Since your code will actually be executed at design time, you can simply have it conditionally do something that will make the designer not do anything unpleasant, to the extent that that is possible. To accomplish this you need to be able to detect programmatically that you are running under the designer and you can use DesignerProperties.IsInDesignModeProperty for that as described here:
Detecting design time mode in WPF and Silverlight
I decided to change base class of MyWindow from Window to ContentControl. For our purposes it is sufficient. Each ContentControl is wrapped into a Window when becomes active.

Resources