I have a traditional form layout with a menu bar at the top and status bar at the bottom. When the user selects a menu item, the space in-between (the form's entire remaining client area) gets replaced with a user control - think of an SDI app that can host multiple types of documents.
If you know of a better way to go about this, please chime in. For now, I'm trying to get it to work in a very simplified version with a ContentControl, but I cannot get it to update the screen when its DataContext is set.
Here's the very simple code for ViewModelA. ViewModelB is identical, except for the Bs.
namespace Dynamic_ContentControl
{
public class ViewModelA: ViewModelBase
{
public ViewModelA()
{
DisplayName = "This is A";
}
}
}
The main window is very simple. It basically declares a property to hold the view model of the hosted control and exposes two commands to assign view models A or B.
namespace Dynamic_ContentControl
{
public class MainViewModel: ViewModelBase
{
private ViewModelBase clientContent = null;
public ICommand ShowA { get; private set; }
public ICommand ShowB { get; private set; }
public ViewModelBase ClientContent {
get
{
return clientContent;
}
private set
{
clientContent = value;
OnPropertyChanged("ClientContent");
}
}
public MainViewModel()
{
ShowA = new RelayCommand((obj) =>
{
ClientContent = new ViewModelA();
});
ShowB = new RelayCommand((obj) =>
{
ClientContent = new ViewModelB();
});
}
}
}
Finally, the XAML declares a ContentControl and sets its ContentTemplate to a DataTemplate called ClientAreaTemplate, whose ContentPresenter points to another DataTemplate, named TextBlockLayout:
<Window x:Class="Dynamic_ContentControl.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:Dynamic_ContentControl"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<vm:MainViewModel />
</Window.DataContext>
<Window.Resources>
<DataTemplate x:Key="TextBlockLayout">
<TextBlock Text="{Binding Path=DisplayName}" />
</DataTemplate>
<DataTemplate x:Key="ButtonLayout">
<Button Content="{Binding Path=DisplayName}" />
</DataTemplate>
<DataTemplate x:Key="CheckBoxLayout">
<CheckBox Content="{Binding Path=DisplayName}" />
</DataTemplate>
<DataTemplate x:Key="ClientAreaTemplate">
<ContentPresenter x:Name="ContentArea" ContentTemplate="{StaticResource ResourceKey=TextBlockLayout}"/>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Path=DataContext}"
Value="{x:Type vm:ViewModelB}">
<Setter TargetName="ContentArea"
Property="ContentTemplate"
Value="{StaticResource ResourceKey=ButtonLayout}" />
</DataTrigger>
<DataTrigger Binding="{Binding Path=DataContext}"
Value="{x:Type vm:ViewModelB}">
<Setter TargetName="ContentArea"
Property="ContentTemplate"
Value="{StaticResource ResourceKey=CheckBoxLayout}" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</Window.Resources>
<Grid>
<Button Content="Show A"
Command="{Binding Path=ShowA}"
HorizontalAlignment="Left"
Margin="10,10,0,0"
VerticalAlignment="Top"
Width="75" />
<Button Content="Show B"
Command="{Binding ShowB}"
HorizontalAlignment="Left"
Margin="90,10,0,0"
VerticalAlignment="Top"
Width="75" />
<Label Content="{Binding Path=ClientContent.DisplayName}"
HorizontalAlignment="Left"
Margin="170,8,0,0"
VerticalAlignment="Top" />
<ContentControl DataContext="{Binding Path=ClientContent}"
Content="{Binding}"
ContentTemplate="{StaticResource ResourceKey=ClientAreaTemplate}"
HorizontalAlignment="Left"
Margin="10,37,0,0"
VerticalAlignment="Top"
Height="198"
Width="211" />
</Grid>
</Window>
Expected behaviour
When the screen opens, I want TextBoxLayout to display. If the user then clicks on one of the two buttons, it should load either a ButtonLayout or CheckBoxLayout, depending on the actual runtime type of the view model that is assigned.
Actual behaviour
The screen opens with the TextBoxLayout loaded, but it never changes to another type as I click the buttons.
I think the problem is the way the DataTrigger tries to compare with the type, but there are no binding messages at all the Output window.
In this situation, you need to use DataTemplateSelector:
Provides a way to choose a DataTemplate based on the data object and the data-bound element.
Here is a version of dynamic DataTemplateSelector which returns a desired DataTemplate depending on the type:
/// <summary>
/// Provides a means to specify DataTemplates to be selected from within WPF code
/// </summary>
public class DynamicTemplateSelector : DataTemplateSelector
{
/// <summary>
/// Generic attached property specifying <see cref="Template"/>s
/// used by the <see cref="DynamicTemplateSelector"/>
/// </summary>
/// <remarks>
/// This attached property will allow you to set the templates you wish to be available whenever
/// a control's TemplateSelector is set to an instance of <see cref="DynamicTemplateSelector"/>
/// </remarks>
public static readonly DependencyProperty TemplatesProperty =
DependencyProperty.RegisterAttached("Templates", typeof(TemplateCollection), typeof(DataTemplateSelector),
new FrameworkPropertyMetadata(new TemplateCollection(), FrameworkPropertyMetadataOptions.Inherits));
/// <summary>
/// Gets the value of the <paramref name="element"/>'s attached <see cref="TemplatesProperty"/>
/// </summary>
/// <param name="element">The <see cref="UIElement"/> who's attached template's property you wish to retrieve</param>
/// <returns>The templates used by the givem <paramref name="element"/>
/// when using the <see cref="DynamicTemplateSelector"/></returns>
public static TemplateCollection GetTemplates(UIElement element)
{
return (TemplateCollection)element.GetValue(TemplatesProperty);
}
/// <summary>
/// Sets the value of the <paramref name="element"/>'s attached <see cref="TemplatesProperty"/>
/// </summary>
/// <param name="element">The element to set the property on</param>
/// <param name="collection">The collection of <see cref="Template"/>s to apply to this element</param>
public static void SetTemplates(UIElement element, TemplateCollection collection)
{
element.SetValue(TemplatesProperty, collection);
}
/// <summary>
/// Overriden base method to allow the selection of the correct DataTemplate
/// </summary>
/// <param name="item">The item for which the template should be retrieved</param>
/// <param name="container">The object containing the current item</param>
/// <returns>The <see cref="DataTemplate"/> to use when rendering the <paramref name="item"/></returns>
public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
{
//This should ensure that the item we are getting is in fact capable of holding our property
//before we attempt to retrieve it.
if (!(container is UIElement))
return base.SelectTemplate(item, container);
//First, we gather all the templates associated with the current control through our dependency property
TemplateCollection templates = GetTemplates(container as UIElement);
if (templates == null || templates.Count == 0)
base.SelectTemplate(item, container);
//Then we go through them checking if any of them match our criteria
foreach (var template in templates)
//In this case, we are checking whether the type of the item
//is the same as the type supported by our DataTemplate
if (template.Value.IsInstanceOfType(item))
//And if it is, then we return that DataTemplate
return template.DataTemplate;
//If all else fails, then we go back to using the default DataTemplate
return base.SelectTemplate(item, container);
}
}
/// <summary>
/// Holds a collection of <see cref="Template"/> items
/// for application as a control's DataTemplate.
/// </summary>
public class TemplateCollection : List<Template>
{
}
/// <summary>
/// Provides a link between a value and a <see cref="DataTemplate"/>
/// for the <see cref="DynamicTemplateSelector"/>
/// </summary>
/// <remarks>
/// In this case, our value is a <see cref="System.Type"/> which we are attempting to match
/// to a <see cref="DataTemplate"/>
/// </remarks>
public class Template : DependencyObject
{
/// <summary>
/// Provides the value used to match this <see cref="DataTemplate"/> to an item
/// </summary>
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(Type), typeof(Template));
/// <summary>
/// Provides the <see cref="DataTemplate"/> used to render items matching the <see cref="Value"/>
/// </summary>
public static readonly DependencyProperty DataTemplateProperty =
DependencyProperty.Register("DataTemplate", typeof(DataTemplate), typeof(Template));
/// <summary>
/// Gets or Sets the value used to match this <see cref="DataTemplate"/> to an item
/// </summary>
public Type Value
{ get { return (Type)GetValue(ValueProperty); } set { SetValue(ValueProperty, value); } }
/// <summary>
/// Gets or Sets the <see cref="DataTemplate"/> used to render items matching the <see cref="Value"/>
/// </summary>
public DataTemplate DataTemplate
{ get { return (DataTemplate)GetValue(DataTemplateProperty); } set { SetValue(DataTemplateProperty, value); } }
}
Example of using
<local:DynamicTemplateSelector x:Key="MyTemplateSelector" />
<DataTemplate x:Key="StringTemplate">
<TextBlock>
<Run Text="String: " />
<Run Text="{Binding}" />
</TextBlock>
</DataTemplate>
<DataTemplate x:Key="Int32Template">
<TextBlock>
<Run Text="Int32: " />
<Run Text="{Binding}" />
</TextBlock>
</DataTemplate>
<Style x:Key="MyListStyle" TargetType="ListView">
<Setter Property="ItemTemplateSelector" Value="{StaticResource MyTemplateSelector}"/>
<Setter Property="local:DynamicTemplateSelector.Templates">
<Setter.Value>
<local:Templates>
<local:Template Value={x:Type String} DataTemplate={StaticResource StringTemplate}/>
<local:Template Value={x:Type Int32} DataTemplate={StaticResource Int32Template}/>
</local:Templates>
</Setter.Value>
</Setter>
</Style>
Related
I have to validate some Properties, before I try to save my Entity into Database.
Problem:
Programmstart: Validation error is shown of textbox in tabitem1
User select: Tabitem2 in the View
User select: Tabitem1 in the View
Validation error of empty textbox is not shown in tabitem1 anymore.
Excepted behavior:
Validation error shall be shown every time also if the user changes the selected tabitem.
Tools / Frameworks used:
Prism 6.3 (New Project with Templatepack PrismUnity
Prism.Validation (https://github.com/mfe-/Prism.Validation)
Questions:
Why the DataAnnoation is not shown anymore after selection between the different tabitems? The ViewModel property hasErrors is true.
How I can restart the evaluation, if the user selected tabitem1 again?
View:
<Window x:Class="PrismUnityApp1TestValidation.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
Title="{Binding Title}" Height="350" Width="525">
<StackPanel>
<!--<ContentControl prism:RegionManager.RegionName="ContentRegion" />-->
<TabControl>
<TabItem>
<TabItem.Content>
<TextBox Height="50" Text="{Binding TestText, ValidatesOnDataErrors=True, NotifyOnValidationError=True, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"></TextBox>
</TabItem.Content>
</TabItem>
<TabItem>
<TabItem.Content>
<TextBlock Text="TabItem2"></TextBlock>
</TabItem.Content>
</TabItem>
</TabControl>
</StackPanel>
</Window>
ViewModel:
using System.ComponentModel.DataAnnotations;
using Prism.Mvvm;
using Prism.Validation;
namespace PrismUnityApp1TestValidation.ViewModels
{
public class MainWindowViewModel : ValidatableBindableBase
{
private string _title = "Prism Unity Application";
public string Title
{
get { return _title; }
set { SetProperty(ref _title, value); }
}
private string _testtext;
[Required]
public string TestText
{
get { return _testtext; }
set { SetProperty(ref _testtext, value); }
}
public MainWindowViewModel()
{
}
}
}
ValidatableBindableBase (NugetPackage Prism.Validation):
namespace Prism.Validation
{
/// <summary>
/// The IValidatableBindableBase interface was created to add validation support for model classes that contain validation rules.
/// The default implementation of IValidatableBindableBase is the ValidatableBindableBase class, which contains the logic to run the validation rules of the
/// instance of a model class and return the results of this validation as a list of properties' errors.
/// </summary>
// Documentation on validating user input is at http://go.microsoft.com/fwlink/?LinkID=288817&clcid=0x409
public class ValidatableBindableBase : BindableBase, IValidatableBindableBase, INotifyDataErrorInfo
{
private readonly BindableValidator _bindableValidator;
/// <summary>
/// Initializes a new instance of the <see cref="ValidatableBindableBase"/> class.
/// </summary>
public ValidatableBindableBase()
{
_bindableValidator = new BindableValidator(this);
}
/// <summary>
/// Gets or sets a value indicating whether this instance is validation enabled.
/// </summary>
/// <value>
/// <c>true</c> if validation is enabled for this instance; otherwise, <c>false</c>.
/// </value>
public bool IsValidationEnabled
{
get { return _bindableValidator.IsValidationEnabled; }
set { _bindableValidator.IsValidationEnabled = value; }
}
/// <summary>
/// Returns the BindableValidator instance that has an indexer property.
/// </summary>
/// <value>
/// The Bindable Validator Indexer property.
/// </value>
public BindableValidator Errors
{
get
{
return _bindableValidator;
}
}
/// <summary>
/// Gets a value that indicates whether the entity has validation errors.
/// </summary>
/// <value>
/// <c>true</c> if this instance contains validation errors; otherwise, <c>false</c>.
/// </value>
public bool HasErrors
{
get
{
return !ValidateProperties();
}
}
/// <summary>
/// Occurs when the Errors collection changed because new errors were added or old errors were fixed.
/// </summary>
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged
{
add { _bindableValidator.ErrorsChanged += value; }
remove { _bindableValidator.ErrorsChanged -= value; }
}
/// <summary>
/// Gets all errors.
/// </summary>
/// <returns> A ReadOnlyDictionary that's key is a property name and the value is a ReadOnlyCollection of the error strings.</returns>
public ReadOnlyDictionary<string, ReadOnlyCollection<string>> GetAllErrors()
{
return _bindableValidator.GetAllErrors();
}
/// <summary>
/// Validates the properties of the current instance.
/// </summary>
/// <returns>
/// Returns <c>true</c> if all properties pass the validation rules; otherwise, false.
/// </returns>
public bool ValidateProperties()
{
return _bindableValidator.ValidateProperties();
}
/// <summary>
/// Validates a single property with the given name of the current instance.
/// </summary>
/// <param name="propertyName">The property to be validated.</param>
/// <returns>Returns <c>true</c> if the property passes the validation rules; otherwise, false.</returns>
public bool ValidateProperty(string propertyName)
{
return !_bindableValidator.IsValidationEnabled // don't fail if validation is disabled
|| _bindableValidator.ValidateProperty(propertyName);
}
/// <summary>
/// Sets the error collection of this instance.
/// </summary>
/// <param name="entityErrors">The entity errors.</param>
public void SetAllErrors(IDictionary<string, ReadOnlyCollection<string>> entityErrors)
{
_bindableValidator.SetAllErrors(entityErrors);
}
/// <summary>
/// Checks if a property already matches a desired value. Sets the property and
/// notifies listeners only when necessary. We are overriding this property to ensure that the SetProperty and the ValidateProperty methods are fired in a
/// deterministic way.
/// </summary>
/// <typeparam name="T">Type of the property.</typeparam>
/// <param name="storage">Reference to a property with both getter and setter.</param>
/// <param name="value">Desired value for the property.</param>
/// <param name="propertyName">Name of the property used to notify listeners. This
/// value is optional and can be provided automatically when invoked from compilers that
/// support CallerMemberName.</param>
/// <returns>
/// True if the value was changed, false if the existing value matched the
/// desired value.
/// </returns>
protected override bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
var result = base.SetProperty(ref storage, value, propertyName);
if (result && !string.IsNullOrEmpty(propertyName))
{
if (_bindableValidator.IsValidationEnabled)
{
_bindableValidator.ValidateProperty(propertyName);
}
}
return result;
}
/// <summary>
/// Gets the validation errors for a specified property or for the entire entity.
/// </summary>
/// <param name="propertyName">The name of the property to retrieve validation errors for; or null or Empty, to retrieve entity-level errors.</param>
/// <returns>The validation errors for the property or entity.</returns>
public IEnumerable GetErrors(string propertyName)
{
if (HasErrors==false)
{
return Enumerable.Empty<String>();
}
return _bindableValidator[propertyName];
}
}
}
I found a solution here:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/fb50537c-feec-42dc-8439-dcf78ef8951a/validation-error-and-tab-control?forum=wpf
I changed as mentioned in the post my View.
View:
<Window x:Class="PrismUnityApp1TestValidation.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
Title="{Binding Title}" Height="350" Width="525">
<StackPanel>
<!--<ContentControl prism:RegionManager.RegionName="ContentRegion" />-->
<TabControl>
<TabItem IsSelected="{Binding TabItem1Selected}">
<TabItem.Content>
<AdornerDecorator>
<TextBox Height="50" Text="{Binding TestText, ValidatesOnDataErrors=True, NotifyOnValidationError=True, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"></TextBox>
</AdornerDecorator>
</TabItem.Content>
</TabItem>
<TabItem>
<TabItem.Content>
<TextBlock Text="TabItem2"></TextBlock>
</TabItem.Content>
</TabItem>
</TabControl>
</StackPanel>
</Window>
I have made in a WPF-CustomControlLibrary a CustomControl, which inherits from the RadioButton.
In the constructor of the CustomControl CustomRadioButton i override the DependyProperty IsCheckedProperty with another default value (in my case false).
/// <summary>
/// The constructor.
/// </summary>
static CustomRadioButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomRadioButton), new FrameworkPropertyMetadata(typeof(CustomRadioButton)));
// Override the default value of the base-DependencyProperty.
IsCheckedProperty.OverrideMetadata(typeof(CustomRadioButton), new FrameworkPropertyMetadata(false));
}
As long as i set in the application, where i use the CustomControlLibrary, the property GroupName of the RadioButtons, the grouping mechanism works.
If one RadioButton is enabled after Click, all others (which belong to the same group) are disabled.
But if i don't set the property GroupName, the grouping doesn't work anymore.
If i click on a RadioButton, it will be enabled forever.
How can the grouping be garanteed without explicit setting of the property GroupName?
Thanks in advance!
And here the definition of my CustomControl in Generic.xaml:
<!--Style for the CustomControl CustomRadioButton-->
<Style TargetType="{x:Type local:CustomRadioButton}" BasedOn="{StaticResource {x:Type RadioButton}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomRadioButton}">
<Border BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<RadioButton IsChecked="{TemplateBinding IsChecked}"
GroupName="{TemplateBinding GroupName}"
HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}">
<TextBlock Text="{TemplateBinding Text}"
TextWrapping="Wrap"
TextAlignment="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type RadioButton}},
Path=HorizontalContentAlignment, Converter={StaticResource h2tAlignmentConverter}}"
TextDecorations="{TemplateBinding TextDecorations}"/>
</RadioButton>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
And the code from the CustomControl:
using System.Windows;
using System.Windows.Controls;
namespace WpfDesignerCustomControlLibrary
{
/// <summary>
/// Class for a CustomControl which inherits from RadioButton and has a nested TextBlock for textwrapping.
/// </summary>
public class CustomRadioButton : RadioButton
{
/// <summary>
/// The constructor.
/// </summary>
static CustomRadioButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomRadioButton), new FrameworkPropertyMetadata(typeof(CustomRadioButton)));
// Override the default value of the base-DependencyProperty.
IsCheckedProperty.OverrideMetadata(typeof(CustomRadioButton), new FrameworkPropertyMetadata(false));
}
/// <summary>
/// DependencyProperty for access to the text value.
/// </summary>
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(CustomRadioButton));
/// <summary>
/// DependencyProperty for the textdecorations.
/// </summary>
public static readonly DependencyProperty TextDecorationsProperty =
DependencyProperty.Register("TextDecorations", typeof(TextDecorationCollection), typeof(CustomRadioButton));
/// <summary>
/// DependencyProperty for external access to the property TableName.
/// </summary>
public static readonly DependencyProperty TableNameProperty =
DependencyProperty.Register("TableName", typeof(string), typeof(CustomRadioButton));
/// <summary>
/// Gets or sets the content.
/// </summary>
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
/// <summary>
/// Gets or sets the textdecorations.
/// </summary>
public TextDecorationCollection TextDecorations
{
get { return (TextDecorationCollection)GetValue(TextDecorationsProperty); }
set { SetValue(TextDecorationsProperty, value); }
}
/// <summary>
/// Gets or sets the name of the datatable which is the datasource.
/// </summary>
public string TableName
{
get { return (string)GetValue(TableNameProperty); }
set { SetValue(TableNameProperty, value); }
}
}
}
Meanwhile i decided to override the GroupNameProperty with a default value.
This works as usual and the users have the possibility to change the GroupName, so it even works with multiple groups of RadioButtons.
/// <summary>
/// The constructor.
/// </summary>
static CustomRadioButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomRadioButton),
new FrameworkPropertyMetadata(typeof(CustomRadioButton)));
[...]
// Override the default value of the base-DependencyProperty GroupName, so the RadioButtons are synchronized as usual.
// For usage of multiple groups the property GroupName has be set explicitly - as usual.
GroupNameProperty.OverrideMetadata(typeof(CustomRadioButton),
new FrameworkPropertyMetadata("group0"));
}
Supplement:
Instead of a groupname like "group0" above i can use a blank (" "). This let the RadioButtons work as usual.
But an empty string as groupname doesn't work.
I'm trying to grasp the new compiled bindings, but right at the start I get stopped by this simple problem.
I have Hub control with one HubSection. The content of this section is an ItemsControl that needs to bind to view models' observable collection. I can't get this binding to work as I expect it to.
<Pivot x:Name="rootPivot" Style="{StaticResource TabsStylePivotStyle}">
<PivotItem>
<Hub>
<HubSection Header="News">
<DataTemplate x:DataType="local:HomePage">
<ItemsControl ItemsSource="{x:Bind ViewModel.NewsItems, Mode=OneWay}" />
ViewModel property is just a property and is instantiated before InitializeComponents() call. NewsItems is observable collection inside view model that is filled after the page has loaded - asynchronously (web request).
What am I doing wrong here?
EDIT: Code-behind
HomePage.xaml.cs
/// <summary>
/// Home pag view.
/// </summary>
public sealed partial class HomePage : Page
{
/// <summary>
/// Initializes a new instance of the <see cref="HomePage"/> class.
/// </summary>
public HomePage()
{
// Retrieve view model
this.ViewModel = ViewModelResolver.Home;
// Trigger view model loaded on page loaded
this.Loaded += (sender, args) => this.ViewModel.LoadedAsync();
this.InitializeComponent();
}
/// <summary>
/// Gets the view model.
/// </summary>
/// <value>
/// The view model.
/// </value>
public IHomeViewModel ViewModel { get; }
}
HomePageViewModel.cs
/// <summary>
/// Home view model.
/// </summary>
public sealed class HomeViewModel : IHomeViewModel
{
/// <summary>
/// Occurs on page loaded.
/// </summary>
public async Task LoadedAsync()
{
// Retrieve news items
var news = await new NewsService().GetNewsAsync();
foreach (var newsItem in news)
this.NewsItems.Add(newsItem);
}
/// <summary>
/// Gets the news items.
/// </summary>
/// <value>
/// The news items.
/// </value>
public ObservableCollection<IFeedItem> NewsItems { get; } = new ObservableCollection<IFeedItem>();
}
This is indeed an interesting question. I guess the issue is that, unlike typical DataTemplate like the following (see its parent ListView is binding to some known data Model.Items)
<ListView ItemsSource="{x:Bind Model.Items}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="model:Item">
<Grid>
<TextBlock Text="{x:Bind Name}" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
your top level DataTemplate however, doesn't know where the data comes from.
So the fix is to tell the HubSection to bind the right data - in this case, the HomePage.xaml.cs instance. So, try adding this to your Hub
<Hub DataContext="{x:Bind}">
Or simply add
this.InitializeComponent();
this.DataContext = this;
Either way should fix your issue.
Hello I am trying to set the value of a property of my ListBoxItem, just not sure how to use Binding in this case if someone could help me, I appreciate it since!
Below XAML
<ControlTemplate TargetType="controls:ModernVerticalMenu">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{TemplateBinding ListWidth}"/>
<ColumnDefinition Width="{TemplateBinding ListWidth}"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Border Background="{TemplateBinding BackColor}" Height="{TemplateBinding Height}" BorderThickness="1" BorderBrush="{DynamicResource bordaSuperior}">
<!-- link list -->
<ListBox x:Name="LinkList" ItemsSource="{Binding Links, RelativeSource={RelativeSource TemplatedParent}}"
ScrollViewer.HorizontalScrollBarVisibility="{TemplateBinding ScrollViewer.HorizontalScrollBarVisibility}" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Height="50" Background="Transparent" Width="500">
<Border Name="border" Padding="10">
<Path x:Name="icon" Data="{Binding IconData}" Stretch="Fill" Fill="{DynamicResource Accent}" Width="20" Height="20" HorizontalAlignment="Left" VerticalAlignment="Center" />
</Border>
<TextBlock x:Name="texto" ToolTip="{Binding Tooltip}" Text="{Binding DisplayName}" Margin="45,2,2,2" FontSize="{DynamicResource MediumFontSize}" TextTrimming="CharacterEllipsis" VerticalAlignment="Center" HorizontalAlignment="Left" />
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IconData}" Value="{x:Null}">
<Setter Property="Margin" TargetName="texto">
<Setter.Value>
<Thickness Bottom="2" Top="2" Left="10" Right="2"/>
</Setter.Value>
</Setter>
</DataTrigger>
<Trigger Property="IsMouseOver" Value="true">
<Trigger.Setters>
<Setter Property="Fill" TargetName="icon">
<Setter.Value>
<SolidColorBrush Color="#f2f2f2" />
</Setter.Value>
</Setter>
</Trigger.Setters>
</Trigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="ListBoxItem.IsMouseOver" SourceName="LinkList" Value="true">
<Trigger.Setters>
<Setter Property="SelectedLinkGroup" Value="{Binding Source=LinkList,Path=Children}"/>
</Trigger.Setters>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
In the code below I am trying to set the value SelectedLinkGroup From property to the value of Children referring to the ListBoxItem LinkList.
<Setter Property="SelectedLinkGroup" Value="{Binding Source=LinkList,Path=Children}"/>
using FirstFloor.ModernUI.Presentation;
using System;
using System.Data;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
namespace FirstFloor.ModernUI.Windows.Controls
{
/// <summary>
/// Represents a control that contains multiple pages that share the same space on screen.
/// </summary>
public class ModernVerticalMenu
: Control
{
/// <summary>
/// Identifies the ContentLoader dependency property.
/// </summary>
public static readonly DependencyProperty ContentLoaderProperty = DependencyProperty.Register("ContentLoader", typeof(IContentLoader), typeof(ModernVerticalMenu), new PropertyMetadata(new DefaultContentLoader()));
/// <summary>
/// Identifies the ListWidth dependency property.
/// </summary>
public static readonly DependencyProperty ListWidthProperty = DependencyProperty.Register("ListWidth", typeof(GridLength), typeof(ModernVerticalMenu), new PropertyMetadata(new GridLength(170)));
/// <summary>
/// Identifies the Links dependency property.
/// </summary>
public static readonly DependencyProperty LinksProperty = DependencyProperty.Register("Links", typeof(LinkCollection), typeof(ModernVerticalMenu), new PropertyMetadata(OnLinksChanged));
/// <summary>
/// Identifies the SelectedSource dependency property.
/// </summary>
public static readonly DependencyProperty SelectedSourceProperty = DependencyProperty.Register("SelectedSource", typeof(Uri), typeof(ModernVerticalMenu), new PropertyMetadata(OnSelectedSourceChanged));
/// <summary>
/// Defines the SelectedLinkGroup dependency property.
/// </summary>
public static readonly DependencyProperty SelectedLinkGroupProperty = DependencyProperty.Register("SelectedLinkGroup", typeof(LinkCollection), typeof(ModernVerticalMenu), new PropertyMetadata(OnSelectedLinkGroupChanged));
/// <summary>
/// Defines the SelectedLink dependency property.
/// </summary>
public static readonly DependencyProperty SelectedLinkProperty = DependencyProperty.Register("SelectedLink", typeof(Link), typeof(ModernVerticalMenu), new PropertyMetadata(OnSelectedLinkChanged));
/// <summary>
/// Defines the SelectedLink dependency property.
/// </summary>
public static readonly DependencyProperty BackColorProperty = DependencyProperty.Register("BackColor", typeof(SolidColorBrush), typeof(ModernVerticalMenu), new PropertyMetadata(null));
/// <summary>
/// Occurs when the selected source has changed.
/// </summary>
public event EventHandler<SourceEventArgs> SelectedSourceChanged;
private ListBox linkList;
/// <summary>
/// Initializes a new instance of the <see cref="ModernVerticalMenu"/> control.
/// </summary>
public ModernVerticalMenu()
{
this.DefaultStyleKey = typeof(ModernVerticalMenu);
// this.BackColor = new SolidColorBrush(Color.FromRgb(0,0,255));
// create a default links collection
SetCurrentValue(LinksProperty, new LinkCollection());
}
private static void OnSelectedLinkGroupChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
// retrieve the selected link from the group
var group = (LinkCollection)e.NewValue; // cria uma nova instancia do grupo
Link selectedLink = null; //cria um link selecionado
if (group != null)
{ //se o grupo copiado existe
selectedLink = group.FirstOrDefault();
}
// update the selected link
((ModernVerticalMenu)o).SetCurrentValue(SelectedLinkProperty, selectedLink);
}
private static void OnSelectedLinkChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
// update selected source
var newValue = (Link)e.NewValue;
Uri selectedSource = null;
if (newValue != null)
{
selectedSource = newValue.Source;
}
((ModernVerticalMenu)o).SetCurrentValue(SelectedSourceProperty, selectedSource);
}
private static void OnLinksChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
((ModernVerticalMenu)o).UpdateSelection();
}
private static void OnSelectedSourceChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
((ModernVerticalMenu)o).OnSelectedSourceChanged((Uri)e.OldValue, (Uri)e.NewValue);
}
private void OnSelectedSourceChanged(Uri oldValue, Uri newValue)
{
UpdateSelection();
// raise SelectedSourceChanged event
var handler = this.SelectedSourceChanged;
if (handler != null) {
handler(this, new SourceEventArgs(newValue));
}
}
private void UpdateSelection()
{
if (this.linkList == null || this.Links == null) {
return;
}
// sync list selection with current source
this.linkList.SelectedItem = this.Links.FirstOrDefault(l => l.Source == this.SelectedSource);
// SetValue(SelectedLinkGroupProperty, this.Links.FirstOrDefault(l => l.Children == this.SelectedLinkGroup));
if (this.Links.FirstOrDefault(l => l.Children == this.SelectedLinkGroup) != null) { }
}
/// <summary>
/// When overridden in a derived class, is invoked whenever application code or internal processes call System.Windows.FrameworkElement.ApplyTemplate().
/// </summary>
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
if (this.linkList != null) {
this.linkList.SelectionChanged -= OnLinkListSelectionChanged;
}
this.linkList = GetTemplateChild("LinkList") as ListBox;
if (this.linkList != null) {
this.linkList.SelectionChanged += OnLinkListSelectionChanged;
}
UpdateSelection();
}
private void OnLinkListSelectionChanged(object sender, SelectionChangedEventArgs e)
{
//
var link = this.linkList.SelectedItem as Link;
if (link != null && link.Source != this.SelectedSource)
{
SetCurrentValue(SelectedSourceProperty, link.Source);
SetCurrentValue(SelectedLinkGroupProperty, link.Children);
}
}
/// <summary>
/// Gets or sets the content loader.
/// </summary>
public IContentLoader ContentLoader
{
get { return (IContentLoader)GetValue(ContentLoaderProperty); }
set { SetValue(ContentLoaderProperty, value); }
}
/// <summary>
/// Gets or sets the collection of links that define the available content in this tab.
/// </summary>
public LinkCollection Links
{
get { return (LinkCollection)GetValue(LinksProperty); }
set { SetValue(LinksProperty, value); }
}
/// <summary>
/// Gets or sets the collection of links that define the available content in this tab.
/// </summary>
public LinkCollection SelectedLinkGroup
{
get { return (LinkCollection)GetValue(SelectedLinkGroupProperty); }
set { SetValue(SelectedLinkGroupProperty, value); }
}
/// <summary>
/// Gets or sets the collection of links that define the available content in this tab.
/// </summary>
public Link SelectedLink
{
get { return (Link)GetValue(SelectedLinkProperty); }
set { SetValue(SelectedLinkProperty, value); }
}
/// <summary>
/// Gets or sets the width of the list when Layout is set to List.
/// </summary>
/// <value>
/// The width of the list.
/// </value>
public GridLength ListWidth
{
get { return (GridLength)GetValue(ListWidthProperty); }
set { SetValue(ListWidthProperty, value); }
}
/// <summary>
/// Gets or sets the source URI of the selected link.
/// </summary>
/// <value>The source URI of the selected link.</value>
public Uri SelectedSource
{
get { return (Uri)GetValue(SelectedSourceProperty); }
set { SetValue(SelectedSourceProperty, value); }
}
/// <summary>
/// Gets or sets the source URI of the selected link.
/// </summary>
/// <value>The source URI of the selected link.</value>
public SolidColorBrush BackColor
{
get { return (SolidColorBrush)GetValue(BackColorProperty); }
set { SetValue(BackColorProperty, value); }
}
}
}
From my understanding of the code, you are trying to set the SelectedLinkGroup property to the items in your LinkList when your mouse is over a ListBoxItem.
As your LinkList's ItemsSource is bound to the Links property on your control you should be able to bind directly to this property to obtain the same result. The following code does just that.
Value="{Binding Links, RelativeSource={RelativeSource TemplatedParent}}"
Alternatively you could bind to the LinkList Items directly.
Value="{Binding ElementName=LinkList, Path=ItemsSource}"
Here you specify the name of the element to bind to and the property on that element.
I want a TextBox with a WaterMark text. I use this solution, which works fine as provided.
Since I have a couple TextBoxes in the control I want to make it a bit dynamic. So I use ( the first time) an attached property, but I can't make it work. No compile errors, but in XAML the Tag Statement can not be resolved ... Content={Binding Path=view:SomeClass.Tag, RelativeSource=...
What is wrong here?
I did this in XAML
<StackPanel Grid.Row="1" TextBlock.FontSize="12">
<TextBox Style="{DynamicResource TextBoxWaterMark}" view:SomeClass.Tag="Search" />
</StackPanel>
Style
<RibbonWindow.Resources>
<Style xmlns:sys="clr-namespace:System;assembly=mscorlib"
x:Key="TextBoxWaterMark"
TargetType="{x:Type TextBox}">
<Style.Resources>
<VisualBrush x:Key="CueBannerBrush"
AlignmentX="Left"
AlignmentY="Center"
Stretch="None">
<VisualBrush.Visual>
<Label Content="{Binding Path=view:SomeClass.Tag, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type view:SomeClass}}}" Foreground="LightGray" />
</VisualBrush.Visual>
</VisualBrush>
</Style.Resources>
<Style.Triggers>
<Trigger Property="Text" Value="{x:Static sys:String.Empty}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
<Trigger Property="Text" Value="{x:Null}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
<Trigger Property="IsMouseCaptured" Value="True">
<Setter Property="Background" Value="White" />
</Trigger>
</Style.Triggers>
</Style>
</RibbonWindow.Resources>
DependencyObject
public static class SomeClass
{
public static readonly DependencyProperty TagProperty = DependencyProperty.RegisterAttached(
"Tag",
typeof(object),
typeof(SomeClass),
new FrameworkPropertyMetadata(null));
public static object GetTag(DependencyObject dependencyObject)
{
return dependencyObject.GetValue(TagProperty);
}
public static void SetTag(DependencyObject dependencyObject, object value)
{
dependencyObject.SetValue(TagProperty, value);
}
}
You Can create such type attached property. here see how.
Mostly peoples looking for watermask textboxs what about combobo items controls etc. lets cover these all at once.
create AttachedProperty like .
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
/// <summary>
/// Class that provides the Watermark attached property
/// </summary>
public static class WatermarkService
{
/// <summary>
/// Watermark Attached Dependency Property
/// </summary>
public static readonly DependencyProperty WatermarkProperty = DependencyProperty.RegisterAttached(
"Watermark",
typeof(object),
typeof(WatermarkService),
new FrameworkPropertyMetadata((object)null, new PropertyChangedCallback(OnWatermarkChanged)));
#region Private Fields
/// <summary>
/// Dictionary of ItemsControls
/// </summary>
private static readonly Dictionary<object, ItemsControl> itemsControls = new Dictionary<object, ItemsControl>();
#endregion
/// <summary>
/// Gets the Watermark property. This dependency property indicates the watermark for the control.
/// </summary>
/// <param name="d"><see cref="DependencyObject"/> to get the property from</param>
/// <returns>The value of the Watermark property</returns>
public static object GetWatermark(DependencyObject d)
{
return (object)d.GetValue(WatermarkProperty);
}
/// <summary>
/// Sets the Watermark property. This dependency property indicates the watermark for the control.
/// </summary>
/// <param name="d"><see cref="DependencyObject"/> to set the property on</param>
/// <param name="value">value of the property</param>
public static void SetWatermark(DependencyObject d, object value)
{
d.SetValue(WatermarkProperty, value);
}
/// <summary>
/// Handles changes to the Watermark property.
/// </summary>
/// <param name="d"><see cref="DependencyObject"/> that fired the event</param>
/// <param name="e">A <see cref="DependencyPropertyChangedEventArgs"/> that contains the event data.</param>
private static void OnWatermarkChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Control control = (Control)d;
control.Loaded += Control_Loaded;
if (d is ComboBox || d is TextBox)
{
control.GotKeyboardFocus += Control_GotKeyboardFocus;
control.LostKeyboardFocus += Control_Loaded;
}
if (d is ItemsControl && !(d is ComboBox))
{
ItemsControl i = (ItemsControl)d;
// for Items property
i.ItemContainerGenerator.ItemsChanged += ItemsChanged;
itemsControls.Add(i.ItemContainerGenerator, i);
// for ItemsSource property
DependencyPropertyDescriptor prop = DependencyPropertyDescriptor.FromProperty(ItemsControl.ItemsSourceProperty, i.GetType());
prop.AddValueChanged(i, ItemsSourceChanged);
}
}
#region Event Handlers
/// <summary>
/// Handle the GotFocus event on the control
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">A <see cref="RoutedEventArgs"/> that contains the event data.</param>
private static void Control_GotKeyboardFocus(object sender, RoutedEventArgs e)
{
Control c = (Control)sender;
if (ShouldShowWatermark(c))
{
RemoveWatermark(c);
}
}
/// <summary>
/// Handle the Loaded and LostFocus event on the control
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">A <see cref="RoutedEventArgs"/> that contains the event data.</param>
private static void Control_Loaded(object sender, RoutedEventArgs e)
{
Control control = (Control)sender;
if (ShouldShowWatermark(control))
{
ShowWatermark(control);
}
}
/// <summary>
/// Event handler for the items source changed event
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">A <see cref="EventArgs"/> that contains the event data.</param>
private static void ItemsSourceChanged(object sender, EventArgs e)
{
ItemsControl c = (ItemsControl)sender;
if (c.ItemsSource != null)
{
if (ShouldShowWatermark(c))
{
ShowWatermark(c);
}
else
{
RemoveWatermark(c);
}
}
else
{
ShowWatermark(c);
}
}
/// <summary>
/// Event handler for the items changed event
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">A <see cref="ItemsChangedEventArgs"/> that contains the event data.</param>
private static void ItemsChanged(object sender, ItemsChangedEventArgs e)
{
ItemsControl control;
if (itemsControls.TryGetValue(sender, out control))
{
if (ShouldShowWatermark(control))
{
ShowWatermark(control);
}
else
{
RemoveWatermark(control);
}
}
}
#endregion
#region Helper Methods
/// <summary>
/// Remove the watermark from the specified element
/// </summary>
/// <param name="control">Element to remove the watermark from</param>
private static void RemoveWatermark(UIElement control)
{
AdornerLayer layer = AdornerLayer.GetAdornerLayer(control);
// layer could be null if control is no longer in the visual tree
if (layer != null)
{
Adorner[] adorners = layer.GetAdorners(control);
if (adorners == null)
{
return;
}
foreach (Adorner adorner in adorners)
{
if (adorner is WatermarkAdorner)
{
adorner.Visibility = Visibility.Hidden;
layer.Remove(adorner);
}
}
}
}
/// <summary>
/// Show the watermark on the specified control
/// </summary>
/// <param name="control">Control to show the watermark on</param>
private static void ShowWatermark(Control control)
{
AdornerLayer layer = AdornerLayer.GetAdornerLayer(control);
// layer could be null if control is no longer in the visual tree
if (layer != null)
{
layer.Add(new WatermarkAdorner(control, GetWatermark(control)));
}
}
/// <summary>
/// Indicates whether or not the watermark should be shown on the specified control
/// </summary>
/// <param name="c"><see cref="Control"/> to test</param>
/// <returns>true if the watermark should be shown; false otherwise</returns>
private static bool ShouldShowWatermark(Control c)
{
if (c is ComboBox)
{
return (c as ComboBox).Text == string.Empty;
}
else if (c is TextBoxBase)
{
return (c as TextBox).Text == string.Empty;
}
else if (c is ItemsControl)
{
return (c as ItemsControl).Items.Count == 0;
}
else
{
return false;
}
}
#endregion
}
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
/// <summary>
/// Adorner for the watermark
/// </summary>
internal class WatermarkAdorner : Adorner
{
#region Private Fields
/// <summary>
/// <see cref="ContentPresenter"/> that holds the watermark
/// </summary>
private readonly ContentPresenter contentPresenter;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="WatermarkAdorner"/> class
/// </summary>
/// <param name="adornedElement"><see cref="UIElement"/> to be adorned</param>
/// <param name="watermark">The watermark</param>
public WatermarkAdorner(UIElement adornedElement, object watermark) :
base(adornedElement)
{
this.IsHitTestVisible = false;
this.contentPresenter = new ContentPresenter();
this.contentPresenter.Content = watermark;
this.contentPresenter.Opacity = 0.5;
this.contentPresenter.Margin = new Thickness(Control.Margin.Left + Control.Padding.Left, Control.Margin.Top + Control.Padding.Top, 0, 0);
if (this.Control is ItemsControl && !(this.Control is ComboBox))
{
this.contentPresenter.VerticalAlignment = VerticalAlignment.Center;
this.contentPresenter.HorizontalAlignment = HorizontalAlignment.Center;
}
// Hide the control adorner when the adorned element is hidden
Binding binding = new Binding("IsVisible");
binding.Source = adornedElement;
binding.Converter = new BooleanToVisibilityConverter();
this.SetBinding(VisibilityProperty, binding);
}
#endregion
#region Protected Properties
/// <summary>
/// Gets the number of children for the <see cref="ContainerVisual"/>.
/// </summary>
protected override int VisualChildrenCount
{
get { return 1; }
}
#endregion
#region Private Properties
/// <summary>
/// Gets the control that is being adorned
/// </summary>
private Control Control
{
get { return (Control)this.AdornedElement; }
}
#endregion
#region Protected Overrides
/// <summary>
/// Returns a specified child <see cref="Visual"/> for the parent <see cref="ContainerVisual"/>.
/// </summary>
/// <param name="index">A 32-bit signed integer that represents the index value of the child <see cref="Visual"/>. The value of index must be between 0 and <see cref="VisualChildrenCount"/> - 1.</param>
/// <returns>The child <see cref="Visual"/>.</returns>
protected override Visual GetVisualChild(int index)
{
return this.contentPresenter;
}
/// <summary>
/// Implements any custom measuring behavior for the adorner.
/// </summary>
/// <param name="constraint">A size to constrain the adorner to.</param>
/// <returns>A <see cref="Size"/> object representing the amount of layout space needed by the adorner.</returns>
protected override Size MeasureOverride(Size constraint)
{
// Here's the secret to getting the adorner to cover the whole control
this.contentPresenter.Measure(Control.RenderSize);
return Control.RenderSize;
}
/// <summary>
/// When overridden in a derived class, positions child elements and determines a size for a <see cref="FrameworkElement"/> derived class.
/// </summary>
/// <param name="finalSize">The final area within the parent that this element should use to arrange itself and its children.</param>
/// <returns>The actual size used.</returns>
protected override Size ArrangeOverride(Size finalSize)
{
this.contentPresenter.Arrange(new Rect(finalSize));
return finalSize;
}
#endregion
}
Sample to Use this attached Property.
<Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Height="403"
Width="346"
Title="Window1">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<AdornerDecorator Grid.Row="0">
<TextBox VerticalAlignment="Center" >
<local:WatermarkService.Watermark>
<TextBlock VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="12">TextBox Water Mask </TextBlock>
</local:WatermarkService.Watermark>
</TextBox>
</AdornerDecorator>
<AdornerDecorator Grid.Row="1">
<ComboBox ItemsSource="{Binding Items}">
<local:WatermarkService.Watermark>
<TextBlock VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="12">Combo Box WaterMask</TextBlock>
</local:WatermarkService.Watermark>
</ComboBox>
</AdornerDecorator>
</Grid>
</Window>
For attached properties you need to use parentheses in your binding path:
<Label Content="{Binding Path=(view:SomeClass.Tag)}" />
This is written here along with explanations on how to bind to other types, such as indexers and collection views.