I have a converter in which I want to be able to change the value to Visibility.Collapsed when in DesignMode. Right it is ignoring the GetIsInDesignMode.
Also, I am binding the VM via dependency injectio (prism)
Converter:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
return Visibility.Collapsed;
if (value != null && value is AllowedSourceCode)
{
var allowedSourceCode = (AllowedSourceCode)value;
if (value == null)
return Visibility.Visible;
else if (allowedSourceCode.SupportedSourceCodes.Contains(allowedSourceCode.SelectedSourceCode))
{
return Visibility.Collapsed;
}
else
return Visibility.Visible;
}
return Visibility.Collapsed;
}
View:
<Canvas Visibility="{Binding SupportedSourceCodes,Converter={StaticResource AllowedSourcesConverter}}" Background="Gray" Opacity="0.9"
Grid.Row="0" Grid.Column="0" Grid.RowSpan="3" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Panel.ZIndex="5" >
xaml.cs:
public ACARSubLedgerUC(ACARSubLedgerVM vm)
{
InitializeComponent();
DataContext = vm;
}
What you're doing should work.
I'm guessing you have a viewmodel behind your window and using the converter on a binding to that viewmodel. Please make sure you are setting your data context in XAML and not in code, because if you are setting it in code your converter will never hit in design mode.
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApp1"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="525"
Height="350"
mc:Ignorable="d">
<Window.DataContext>
<local:ViewModel />
</Window.DataContext>
...
</Window>
This ensures bindings are updated at design time and hence your converter will be called.
I wrote a markup extension that makes it way easier to muck around with design time bindings and property values without messing around with the code your view binds to or changing the actual runtime value of a property. The full write up is here: http://www.singulink.com/CodeIndex/post/wpf-visibility-binding-with-design-time-control
It works with visibility as well as most other properties. Usage looks like:
<Grid Visibility="{data:Value {Binding RootObject, Converter={StaticResource NullToVisibilityConverter}}, DesignValue=Visible}">
<TextBlock Background="Red" Text="Testing visibility" />
</Grid>
The extension class:
public class ValueExtension : MarkupExtension
{
public object DesignValue { get; set; } = DependencyProperty.UnsetValue;
[ConstructorArgument("value")]
public object Value { get; set; } = DependencyProperty.UnsetValue;
public ValueExtension() { }
public ValueExtension(object value)
{
Value = value;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
var provideValueTarget = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
var target = provideValueTarget.TargetObject as FrameworkElement;
var value = DesignerProperties.GetIsInDesignMode(target) && DesignValue != DependencyProperty.UnsetValue ? DesignValue : Value;
if (value == DependencyProperty.UnsetValue || value == null)
return value;
if (value is MarkupExtension)
{
return ((MarkupExtension)value).ProvideValue(serviceProvider);
}
var property = provideValueTarget.TargetProperty as DependencyProperty;
if (property.PropertyType.IsInstanceOfType(value))
return value;
return TypeDescriptor.GetConverter(property.PropertyType).ConvertFrom(value);
}
}
Related
I'm trying to bind the Visibility property of a FontIcon to an enum property in my view model using a converter, but for some reason it throws an exception
Unable to cast object of type 'Windows.UI.Xaml.Controls.FontIcon' to type
'Windows.UI.Xaml.Data.Binding'
What I want to achieve is that depending on the current value of CurrentSortOrder hide or show an icon inside the MenuFlyoutItem
View model code:
public class TestViewModel : ViewModelBase
{
private TaskSortType _currentTaskSortOrder = TaskSortType.BY_NAME_ASC;
public TaskSortType CurrentSortOrder
{
get => _currentTaskSortOrder;
set => Set(ref _currentTaskSortOrder, value);
}
}
View:
<Page
x:Class="UWPTests.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:converters="using:UWPTests.Converters"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="using:UWPTests"
xmlns:localModels="using:UWPTests.Models"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
DataContext="{x:Bind ViewModel}"
mc:Ignorable="d">
<Page.Resources>
<converters:TaskSortTypeToVisibilityConverter x:Key="TaskSortTypeToVisibilityConverter" />
</Page.Resources>
<Grid>
<AppBarButton Icon="Sort" Label="Sort">
<AppBarButton.Flyout>
<MenuFlyout>
<MenuFlyoutSubItem Text="By name">
<MenuFlyoutItem Text="Asc">
<MenuFlyoutItem.Icon>
<FontIcon Glyph="" Visibility="{Binding CurrentSortOrder, Mode=OneWay, Converter={StaticResource TaskSortTypeToVisibilityConverter}, ConverterParameter={x:Bind localModels:TaskSortType.BY_NAME_ASC}}" />
</MenuFlyoutItem.Icon>
</MenuFlyoutItem>
<MenuFlyoutItem Text="Desc">
<MenuFlyoutItem.Icon>
<FontIcon Glyph="" Visibility="Collapsed" />
</MenuFlyoutItem.Icon>
</MenuFlyoutItem>
</MenuFlyoutSubItem>
</MenuFlyout>
</AppBarButton.Flyout>
</AppBarButton>
</Grid>
Converter:
public class TaskSortTypeToVisibilityConverter : IValueConverter
{
public Visibility OnTrue { get; set; }
public Visibility OnFalse { get; set; }
public TaskSortTypeToVisibilityConverter()
{
OnFalse = Visibility.Collapsed;
OnTrue = Visibility.Visible;
}
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value is null || parameter is null)
return Visibility.Collapsed;
var currentOrder = (TaskSortType)value;
var targetOrder = (TaskSortType)parameter;
return currentOrder == targetOrder ? OnTrue : OnFalse;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
if (value is Visibility == false)
return DependencyProperty.UnsetValue;
if ((Visibility)value == OnTrue)
return true;
else
return false;
}
}
Any help would be appreciated
Edit:
I get the exception here: this.InitializeComponent();
public sealed partial class MainPage : Page
{
public TestViewModel ViewModel { get; set; }
public MainPage()
{
ViewModel = new TestViewModel();
this.InitializeComponent();
}
}
Edit 2:
public enum TaskSortType
{
BY_NAME_ASC = 0,
BY_NAME_DESC = 1,
BY_UPDATED_DATE_ASC = 2,
BY_UPDATED_DATE_DESC = 3,
}
It seems that i cant use x:Bind directly in the ConverterParameter .. So i ended with the following:
I added in my page resources:
<localModels:TaskSortType x:Key="TaskSortByNameAsc">BY_NAME_ASC</localModels:TaskSortType>
<localModels:TaskSortType x:Key="TaskSortByNameDesc">BY_NAME_DESC</localModels:TaskSortType>
<localModels:TaskSortType x:Key="TaskSortByUpdatedDateAsc">BY_UPDATED_DATE_ASC</localModels:TaskSortType>
<localModels:TaskSortType x:Key="TaskSortByUpdatedDateDesc">BY_UPDATED_DATE_DESC</localModels:TaskSortType>
And then i replaced the ConverterParameter binding with the following:
<FontIcon Glyph="" Visibility="{Binding CurrentSortOrder, Mode=OneWay, Converter={StaticResource TaskSortTypeToVisibilityConverter}, ConverterParameter={StaticResource BY_NAME_ASC}}" />
Another workaround would be to pass the corresponding value in the ConverterParameter, for example ConverterParameter=0 or ConverterParameter="BY_NAME_ASC"and the cast that parameter to the corresponding enum value
I have a visibility converter for a a DataGrid that should hide the grid when the item source for the grid is null. The item source is a property of the class for the window.
Here is partial XAML for the window - the window and visibility converter definition and the data grid:
Window:
<Window x:Name="DiagramWindow"
x:Class="FabricAnalyzer.FabricDiagram"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:FabricAnalyzer"
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
mc:Ignorable="d"
Title="FabricDiagram"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Window.Resources>
<ResourceDictionary>
<local:SwitchThumbColorConverter x:Key="SwitchThumbColor"/>
<local:PortThumbColorConverter x:Key="PortThumbColor"/>
<local:StringLengthVisiblityConverter x:Key="VisConverter"/>
<local:PortListVisiblityConverter x:Key="PortVisConverter"/>
Datagrid:
<Grid Name="FabricGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<DataGrid Name="SVCPortDataGrid" Grid.Column="0" Width="Auto"
Visibility="{Binding Path=PortList, Converter=
{StaticResource PortVisConverter}}"
AutoGenerateColumns="False">
Here is the code behind for the property it should bind to and the VisibilityConverter. the idea is that if the PortList is null - it will be by default - the DataGrid should stay collapsed. I have verified that the PortList is null when I want it to be.
public partial class FabricDiagram : Window
{
public List<PortResult> PortList = null;
lastly the visibilityconverter. I have verified in the debugger that it is not getting called.
public class PortListVisiblityConverter : IValueConverter
{
public Object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null )
{
return Visibility.Collapsed;
}
else
{
return Visibility.Visible;
}
}
public Object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
I've tried changing the XAML to this binding
Visibility="{Binding PortList, Converter={StaticResource PortVisConverter}}"
Your binding is failing, so the converter never runs.
public List<PortResult> PortList = null;
declares a field and you can only bind to properties. Changing to:
public List<PortResult> PortList { get; set; } = null;
will solve your first problem; then you need to use INotifyPropertyChanged if you want changes to that property to propagate to the UI.
As an aside, you could have figured this out if you looked at the output window while running and saw System.Data exceptions. Easiest way to debug binding issues :)
After done with setting up MVVM Light in a Universal Windows App application, I have the following structure, and I wonder what is the cleanest way to do validation in 2017 using UWP and mvvmlight to notify users with errors and possibly reset the textbox value when needed. The only trick is that the Textbox is part of a UserControl (cleaned up unnecessary xaml code for clarity) since it will be used multiple times. Also I added DataAnnotations and ValidationResult for demonstration and not to suggest that this is the best way to do it or that it is working in any way so far.
The code works fine as far as binding and adding and removing values
ViewModel
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Views;
using System;
using System.ComponentModel.DataAnnotations;
public class ValidationTestViewModel : ViewModelBase
{
private int _age;
[Required(ErrorMessage = "Age is required")]
[Range(1, 100, ErrorMessage = "Age should be between 1 to 100")]
[CustomValidation(typeof(int), "ValidateAge")]
public int Age
{
get { return _age; }
set
{
if ((value > 1) && (value =< 100))
_age= value;
}
}
public static ValidationResult ValidateAge(object value, ValidationContext validationContext)
{
return null;
}
}
View
<Page
x:Class="ValidationTest.Views.ValidationTestPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ValidationTest.Views"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
DataContext="{Binding ValidationTestPageInstance, Source={StaticResource Locator}}"
xmlns:views="using:ValidationTest.Views">
<views:NumberEdit TextInControl="{Binding Age, Mode=TwoWay}" />
</Page>
UserControl
<UserControl
x:Class="ValidationTest.Views.Number"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ValidationTest.Views"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Name="userControl1">
<Grid>
<TextBox x:Name="content" Text="{Binding TextInControl, ElementName=userControl1, Mode=TwoWay}"></TextBox>
</Grid>
</UserControl>
UserControl Code Behind:
public partial class NumberEdit : UserControl
{
public string TextInControl
{
get { return (string)GetValue(TextInControlProperty); }
set {
SetValue(TextInControlProperty, value);
}
}
public static readonly DependencyProperty TextInControlProperty =
DependencyProperty.Register("TextInControl", typeof(string),
typeof(NumberEdit), new PropertyMetadata(null));
}
We usually use IDialogService interface in MVVM Light to notify users with errors, there are ShowError method, ShowMessage method and ShowMessageBox method in IDialogService.
We should be able to new a PropertyMetadata instance with a PropertyChangedCallback value, it will be invoked when the effective property value of a dependency property changes. When it is invoked, we can use the ShowMessage method in it.
For example:
public sealed partial class NumberEdit : UserControl
{
public NumberEdit()
{
this.InitializeComponent();
}
public static readonly DependencyProperty TextInControlProperty =
DependencyProperty.Register("TextInControl", typeof(string),
typeof(NumberEdit), new PropertyMetadata(null, new PropertyChangedCallback(StringChanged)));
private static void StringChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
int value;
Int32.TryParse(e.NewValue.ToString(), out value);
if (0 < value && value < 99)
{
}
else
{
var dialog = ServiceLocator.Current.GetInstance<IDialogService>();
dialog.ShowMessage("Age should be between 1 to 100", "Error mesage");
}
}
public string TextInControl
{
get { return (string)GetValue(TextInControlProperty); }
set
{
SetValue(TextInControlProperty, value);
}
}
}
Also if you want to reset the TextBox value, you should be able to use RaisePropertyChanged in the Age property. If we do not use RaisePropertyChanged in the Age property, the TextBox value will not change when the Age value has changed.
For more info about the RaisePropertyChanged, please refer INotifyPropertyChanged interface.
For example:
public int Age
{
get { return _age; }
set
{
if ((value > 1) && (value <= 100))
_age = value;
RaisePropertyChanged("Age");
}
}
Update:
In your Page you should be add to add DataContext in your control.
<Page x:Class="Validation_Using_MVVM_Light_in_a.SecondPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:local="using:Validation_Using_MVVM_Light_in_a"
xmlns:VM="using:Validation_Using_MVVM_Light_in_a.ViewModel">
<Page.Resources>
<VM:ValidationTestViewModel x:Key="MyViewModel" />
</Page.Resources>
<Grid>
<local:NumberEdit DataContext="{StaticResource MyViewModel}" TextInControl="{Binding Age, Mode=TwoWay}" />
</Grid>
</Page>
What you are missing here is a call to Validator.ValidateObject to do the actual validation. This will apply the validation attributes to the data and will also call IValidatableObject.Validate if you have implemented it (you should implement this instead of having ad-hoc functions such as ValidateAge).
Like this:
// Validate using:
// 1. ValidationAttributes attached to this validatable's class, and
// 2. ValidationAttributes attached to the properties of this validatable's class, and
// 3. this.Validate( validationContext)
//
// Note, for entities, a NotSupportedException will be thrown by TryValidateObject if any of
// the primary key fields are changed. Correspondingly the UI should not allow modifying
// primary key fields.
ValidationContext validationContext = new ValidationContext(this);
List<ValidationResult> validationResults = new List<ValidationResult>(64);
bool isValid = Validator.TryValidateObject( this, validationContext, validationResults, true);
Debug.Assert(isValid == (validationResults.Count == 0));
I'm having a simple WPF XAML Window, I need to Create a StaticResource Key with in the following XAML.
The XAML Source Code is
<Window x:Class="WpfApplication1.Trigger"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:super="clr-namespace:WpfApplication1"
Title="Trigger" Height="300" Width="300">
<Grid>
<Border x:Name="m_Border" Width="100" Height="30" HorizontalAlignment="Center" VerticalAlignment="Top" Background="#FFF2FFC6" Margin="0,20,0,0">
<Button x:Name="btn" Content="iApp" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75" Visibility="{Binding IsMouseOver,ElementName=m_Border, Converter={StaticResource BooleanToVisibilityConverterKey}, ConverterParameter=Normal}"/>
</Border>
</Grid>
</Window>
My Converter C# Source Code:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
namespace WpfApplication1
{
public enum BooleanToVisibilityConverterType
{
Normal = 1,
Reverse = 2
}
public class BooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var targertValue = false;
if (value == null)
{
throw new Exception("BooleanToVisibilityConverter - Convert Error");
}
else if (!Boolean.TryParse(value.ToString(), out targertValue))
{
throw new Exception("BooleanToVisibilityConverter - Convert Error");
}
else
{
var parameterValue = BooleanToVisibilityConverterType.Normal;
if (parameter != null)
{
Enum.TryParse<BooleanToVisibilityConverterType>(parameter.ToString(), out parameterValue);
}
if (parameterValue == BooleanToVisibilityConverterType.Reverse)
{
return targertValue ? Visibility.Collapsed : Visibility.Visible;
}
else
{
return targertValue ? Visibility.Visible : Visibility.Collapsed;
}
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var targetValue = Visibility.Collapsed;
if (value == null)
{
throw new Exception("BooleanToVisibilityConverter - ConvertBack Error");
}
else if (!Enum.TryParse<Visibility>(value.ToString(), out targetValue))
{
throw new Exception("BooleanToVisibilityConverter - ConvertBack Error");
}
else
{
var parameterValue = BooleanToVisibilityConverterType.Normal;
if (parameter != null)
{
Enum.TryParse<BooleanToVisibilityConverterType>(parameter.ToString(), out parameterValue);
}
if (parameterValue == BooleanToVisibilityConverterType.Reverse)
{
return targetValue == Visibility.Visible ? false : true;
}
else
{
return targetValue == Visibility.Visible ? true : false;
}
}
}
}
}
I need a Converter Key with Name BooleanToVisibilityConverterKey
for the Converter BooleanToVisibilityConverter
You can define your Converter in the Window.Resources element.
<Window ...
>
<Window.Resources>
<super:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverterKey"/>
</Window.Resources>
...
It could be a better idea to make this converter global. This will save you from having to define the converter in every new Window. It also means that your converter is only instantiated once, therefore improving performance slightly.
To achieve this, define the converter in App.xaml instead.
<Application ...
xmlns:super="clr-namespace:WpfApplication1">
<Application.Resources>
<super:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverterKey"/>
</Application.Resources>
</Application>
You usually put this into the Resources property of the surrounding object, in this case, your Window:
<Window x:Class="WpfApplication1.Trigger"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:super="clr-namespace:WpfApplication1"
Title="Trigger" Height="300" Width="300">
<Window.Resources>
<super:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverterKey"/>
</Window.Resources>
<Grid>
...
Some things to note:
Do not forget to use the appropriate namespace prefix.
Strictly speaking, what is happening here is not merely that you are "defining a key"; you are putting an instance of your converter class into the local resource dictionary and assigning that instance to a key.
By convention, you would not normally name resource keys ...Key explicitly. So-to-speak, in the rest of your XAML document, the resource key is the object stored in the resource. You would name properties that dynamically return certain keys ...Key (such as various of the properties in the SystemColors class).
I understand that the Visibility property of a control cannot be bound to data in the same way that other properties can. It needs some kind of converter(?). In trying to implement the solution from this question I run into a compiler error that says: The resource "BoolToVisible" could not be resolved. I'm guessing that I have to create a ResourceKey named BoolToVisible, I just don't know how.
I'm requesting that someone show me the right way to Bind to the Visibility property of a control.
*The control that I am adding this to is a radio button.
* I have a bool property for isVisible in my Data Model that will be bound to this radio button.
Data Model Property:
private bool _isVisible = true;
public bool IsVisible
{
get { return _isVisible; }
set
{
_isVisible = value;
NotifyPropertyChange(() => IsVisible);
}
}
XAML:
<RadioButton Visibility="{Binding DataModel.IsVisible,Converter={StaticResource ResourceKey=BoolToVisible},RelativeSource={RelativeSource TemplatedParent}}" ... />
Thank you.
2 examples :
The first using a Converter like stated in the question :
public class BooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null || !(value is bool))
return Binding.DoNothing;
return (bool)value ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value;
}
}
in xaml :
<Window x:Class="Stackoverflow.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"
xmlns:local="clr-namespace:Stackoverflow"
>
<Window.Resources>
<local:BooleanToVisibilityConverter x:Key="booleanToVisibiltyConverter"/>
</Window.Resources>
<Grid>
<Button Visibility="{Binding IsSomeThing,Converter={StaticResource booleanToVisibiltyConverter}}"/>
</Grid>
the second :
in your DataContext you can literly hold a Visibility Property
cs :
private Visibility _myControlVisibility;
public Visibility MyControlVisibility
{
get { return _myControlVisibility; }
set { _myControlVisibility = value; }
}
xaml :
<Button Visibility="{Binding MyControlVisibility}"/>
You can binding visibility with a property, you just need to have a Dependency Property of Visibility field as:
Public Property MyVisibility As Windows.Visibility
Get
Return GetValue(MyVisibilityProperty)
End Get
Set(ByVal value As Windows.Visibility)
SetValue(MyVisibilityProperty, value)
End Set
End Property
Public Shared ReadOnly MyVisibilityProperty As DependencyProperty = _
DependencyProperty.Register("MyVisibility", _
GetType(Windows.Visibility), GetType(MyWindow), _
New PropertyMetadata(Nothing))
Then do the binding as the usual (The code is in VB).
Remember that in the New PropertyMetadata you can set an initial state for the object eg:
Public Shared ReadOnly MyVisibilityProperty As DependencyProperty = _
DependencyProperty.Register("MyVisibility", _
GetType(Windows.Visibility), GetType(MyWindow), _
New PropertyMetadata(Windows.Visibility.Hidden))