MenuItem.IsEnabled is bound to whether there is something selected in Listbox or not, but it doesn't update - c#

I have a MenuItem, which should be enabled only if there is something selected in ListBox. I wrote a converter from object to bool, which returns false, if that object == null, and true otherwise. I bound it to ListBox.SelectedItem with my converter, but it doesn't work. Placing a breakpoint in the converter shows, that it never runs. The MenuItem appears always enabled no matter what.
Here is xaml code of the ListBox and of MenuItem
<ListBox Name="TestsListBox"
HorizontalAlignment="Left" Height="93" VerticalAlignment="Top" Width="128"
Margin="0,5,-1.723,0" ItemsSource="{Binding Path=Tests, Mode=OneWay}">
<ListBox.ContextMenu>
<ContextMenu>
<MenuItem Header="Remove" Click="removeTest"
IsEnabled="{Binding ElementName=TestsListBox, Mode=OneWay,
Path=SelectedItem, Converter={StaticResource ObjectToBool}}"/>
</ContextMenu>
</ListBox.ContextMenu>
</ListBox>
Here I show how converter is declared as window's resource
<Window x:Class="WpfApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:ClassesLib="clr-namespace:Laba1;assembly=ClassesLib"
xmlns:local="clr-namespace:WpfApplication"
Title="MainWindow" Height="450" Width="525">
<Window.Resources>
<local:ObjectToBoolConverter x:Key="ObjectToBool"/>
</Window.Resources>
And here is the converter class
namespace WpfApplication
{
class ObjectToBoolConverter: IValueConverter
{
// Converts value to boolean. If value is null, returns false.
// Otherwise returns true
public object Convert(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
if (null == value)
{
return false;
}
return true;
}
public object ConvertBack(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException("This is oneway converter, so ConvertBack is not supported");
}
}
}

RelativeSource and Popup
From here you should be able to find out that the reason ElementName binding doesn't work is because the ContextMenu isn't part of the visual tree as other controls are, and therefore can not take part in such binding scenarios. AFAIK, PopUps have a PlacementTarget property that you can bind to and figure out how to use.

This was how I solved it:
VIEW:
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication2"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:ObjectToBoolConverter x:Key="ObjectToBool"/>
<ContextMenu x:Key="contextMenu" DataContext="{Binding PlacementTarget.SelectedItem, RelativeSource={RelativeSource Self}}">
<MenuItem Header="Remove" Click="removeTest"
IsEnabled="{Binding Path=., Converter={StaticResource ObjectToBool}}"/>
</ContextMenu>
</Window.Resources>
<Grid>
<ListBox Name="TestsListBox"
HorizontalAlignment="Left" Height="93" VerticalAlignment="Top" Width="128"
Margin="0,5,-1.723,0" ContextMenu="{StaticResource ResourceKey=contextMenu}">
</ListBox>
</Grid>
</Window>
CODE BEHIND
using System.Collections.Generic;
using System.Windows;
using System.Windows.Documents;
namespace WpfApplication2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
List<string> teste = new List<string>();
teste.Add("test1");
teste.Add("test3");
teste.Add("test2");
TestsListBox.ItemsSource = teste;
}
private void removeTest(object sender, RoutedEventArgs e)
{
}
}
}
The converter stayed the same.
Regards,

Looks like ElementName property of Binding doesn't do what I thought it does. Also it sucks very much that XAML just ignores and does nothing about incorrect parameters of Binding: it should raise an error instead.
I added DataContext to my ContextMenu, removed ElementName, and it is working now. This is how I changed the code:
<ContextMenu DataContext="{Binding PlacementTarget, RelativeSource={RelativeSource Self}}" >
<MenuItem Header="Add" Click="addTest"/>
<MenuItem Header="Remove" Click="removeTest"
IsEnabled="{Binding Mode=OneWay,
Path=SelectedItem, Converter={StaticResource ObjectToBool}}"/>
</ContextMenu>
Dtex's comment about a duplicate helped me with this, even though I thought I could use ElementName instead of DataContext.

Related

How to raise event at Mainwindow

I have usercontrol which has datagrid .This usercontrol is added to WPF main window.I am handling gridrow selection changed event through bubble event.
<ListBox x:Name="myListBox" Grid.Row="0"
ItemsSource="{Binding Path=_myControl}"
ScrollViewer.VerticalScrollBarVisibility="Auto"
SelectedItem="{Binding CurrentItem}" SelectedIndex="1">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<local:UCSearchEntity GridRowSelectionConfirmed="{Binding Path=UCSearchEntity_GridRowSelectionConfirmed}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
public class MyViewModel:INotifyPropertyChanged
{
}
the error is Provide value on 'System.Windows.Data.Binding' threw an exception.
How can I access this usercontrol event in my mainwindow viewModel ?
You cannot do binding to events like that you have to do something like this on your mainwindow :
<Window DataGrid.GridRowSelectionConfirmed="GridRowSelectionConfirmed">
and GridRowSelectionConfirmed would be a method in your mainwindow
And the xaml above is a snippet in your xaml of the mainwindow.
If you want to stick to using MVVM then you have to start using behaviours but this is a more advanced concept. The behaviour is needed to attach a command that you can databind to an event that otherwise is not bindable like you were trying to do. You see I am making use of interactivity, if you want to do the same you need the blend sdk. An example :
public class AddingNewItemBehavior : Behavior<DataGrid>
{
public static readonly DependencyProperty CommandProperty
= DependencyProperty.Register("Command", typeof(ICommand), typeof(AddingNewItemBehavior), new PropertyMetadata());
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
protected override void OnAttached()
{
AssociatedObject.AddingNewItem += AssociatedObject_OnAddingNewItem;
}
private void AssociatedObject_OnAddingNewItem(object sender, AddingNewItemEventArgs addingNewItemEventArgs)
{
AddingNewItem addingNewItem = new AddingNewItem();
Command.Execute(addingNewItem);
addingNewItemEventArgs.NewItem = addingNewItem.NewItem;
}
}
This is an adding new behaviour I have on a datagrid.
And this is a simplified example where i make use of that behaviour :
<UserControl x:Class="Interstone.Configuratie.Views.GraveerFiguurAdminUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:iCeTechControlLibrary="clr-namespace:ICeTechControlLibrary;assembly=ICeTechControlLibrary"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<DataGrid ItemsSource="{Binding ZandstraalImageTypes.View}" AutoGenerateColumns="False"
VerticalGridLinesBrush="#FFC9CACA" HorizontalGridLinesBrush="#FFC9CACA" RowHeaderWidth="50"
>
<i:Interaction.Behaviors>
<iCeTechControlLibrary:AddingNewItemBehavior Command="{Binding AddingNewCommand}"/>
</i:Interaction.Behaviors>
<DataGrid.Columns>
<DataGridTextColumn Header="Categorie" Binding="{Binding TypeNaam}" Width="*"/>
</DataGrid.Columns>
</DataGrid>
</Grid>

IValueConverter doesn't execute

I have this XAML Code (ErdMenuItem.xaml):
<UserControl x:Class="ErdBuilder.ErdMenuItem"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:erdBuilder="clr-namespace:ErdBuilder"
x:Name="UserControl">
<UserControl.Resources>
<erdBuilder:ByteImageConverter x:Key="imageConverter" />
</UserControl.Resources>
<Image Source="{Binding Converter={StaticResource imageConverter}, ElementName=UserControl, Path=Icon}" />
</UserControl>
If I write:
<Image Source="{Binding Converter={StaticResource imageConverter}, ElementName=UserControl, Path=Icon}" />
Then the Converter will not be executed - I use Breakpoints in the Converter. But if I use this:
<Image Source="{Binding Converter={StaticResource imageConverter}}" />
Then the Converter will be executed. Icon is a Dependency Property of type string. I dont know why the Converter will not be executed as far as I add the DependencyProperty which should bring in the Value which I want to convert. Any Ideas ?
The Icon is here (ErdMenuItem.xaml.cs):
namespace ErdBuilder
{
public partial class ErdMenuItem
{
public static readonly DependencyProperty IconProperty = DependencyProperty.Register("Icon", typeof(string), typeof(ErdMenuItem), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure));
public string Icon
{
get { return (string)GetValue(IconProperty); }
set { SetValue(IconProperty, value); }
}
}
}
That's because there's no data in DataContext. The binding expression returns value of the current DataContext. You can set DataContext for Image by using {Binding Converter={StaticResource imageConverter}, Path=Icon} expression or set it for the root element (UserControl in your case). This option is better, as you can use RelativeSource expression to avoid using explicit names.
<UserControl x:Class="ErdBuilder.ErdMenuItem"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:erdBuilder="clr-namespace:ErdBuilder"
x:Name="UserControl"
DataContext="{Binding RelateSource={RelativeSource Self}}">

How do I manage the width of controls through UserControl parameters?

In short, the goal is to propagate LabelWidth to its children in my UserControl class, PropertyView. See this fragment:
<TabItem.Header>Press</TabItem.Header>
<TabItem.DataContext>
<Binding XPath="press_information"/>
</TabItem.DataContext>
<W3V:PropertyView LabelWidth="200"></W3V:PropertyView>
ANSWER (credit to Athari for his part). To make it work, I needed two elements: In C#, a dependency property:
public double LabelWidth
{ get { return (double)this.GetValue(LabelWidthProperty); }
set { this.SetValue(LabelWidthProperty, value); }
}
public static readonly DependencyProperty LabelWidthProperty =
DependencyProperty.Register(
"LabelWidth", typeof(double), typeof(PropertyView), new PropertyMetadata(100.0)
);
In XAML, the following binding syntax:
<W3V:SimpleControl x:Name="simple" Content="{Binding}"
LabelWidth="{Binding LabelWidth,
RelativeSource={RelativeSource AncestorType=W3V:PropertyView}}" />
What didn't work (my original problem):
See the ????? below in the XAML code. I have NO IDEA what I can put in to make it so the SimpleControl will get a LabelWidth assigned, so that it will set its TextBlock's Width property.
I don't even care what approach is taken, it just needs to deal with the fact that PropertyView is bound to an XML object so it can display its properties, and LabelWidth needs to be a property the control-user sets that gets shoved down into the control. LabelWidth will vary depending on what object is being displayed, so it can't be global.
<UserControl x:Class="W3.Views.PropertyView" ... >
<UserControl.Resources>
</UserControl.Resources>
<StackPanel Margin="2" CanVerticallyScroll="true">
<Border Height="22">
<TextBlock VerticalAlignment="Bottom"
Text="{Binding XPath=#label}"
FontSize="16" FontWeight="Bold" />
</Border>
<ItemsControl ItemsSource="{Binding XPath=*}" Margin="20,0,0,0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<W3V:SimpleControl x:Name="simple"
Content="{Binding}"
LabelWidth=?????? />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</UserControl>
C#:
public partial class PropertyView : UserControl
{
public double LabelWidth
{
get { return (double)this.GetValue(LabelWidthProperty); }
set { this.SetValue(LabelWidthProperty, value); }
}
public static readonly DependencyProperty LabelWidthProperty =
DependencyProperty.Register(
"LabelWidth2", typeof(double), typeof(PropertyView), new PropertyMetadata(0.0)
);
public PropertyView()
{
InitializeComponent();
}
}
I've searched extensively for a solution that deals with this combination of circumstances, tried many things without success (well, success for simpler situations, but not this), and I'm at a loss here.
Answer to edited question
Here's another go for your problem based on refined question. I'm still not 100% sure what you are trying to achieve but maybe the following points you to right direction, at least.
So there's a Window containing only UserControl. This user control is bound to XML file and it has three label fields. One shows node attritube and the following XML file content. First label's width is bound to property in MainWindow and the other to static converter resource inside the UserControl.
MainWindow XAML
<Window x:Class="WpfApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:user="clr-namespace:WpfApplication"
Title="MainWindow" Height="350" Width="600">
<Grid>
<user:XmlUserControl />
</Grid>
</Window>
MainWindow Codebehind
using System;
using System.Windows;
namespace WpfApplication
{
public partial class MainWindow : Window
{
readonly Random _random = new Random();
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
public double ControlWidth
{
get { return _random.Next(200, 600); }
}
}
}
XmlUserControl XAML
<UserControl x:Class="WpfApplication.XmlUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApplication2"
mc:Ignorable="d"
d:DesignHeight="350" d:DesignWidth="350">
<StackPanel>
<StackPanel.Resources>
<XmlDataProvider x:Key="XmlData" XPath="Data/Items" Source="Items.xml" />
<local:NodeWidthConverter x:Key="NodeWidthConverter" />
</StackPanel.Resources>
<ItemsControl>
<ItemsControl.ItemsSource>
<Binding Source="{StaticResource XmlData}" XPath="*"/>
</ItemsControl.ItemsSource>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<Label x:Name="Title" VerticalAlignment="Bottom"
FontWeight="Bold" HorizontalAlignment="Left"
Content="{Binding XPath=#Title}" />
<Label Background="BurlyWood" HorizontalAlignment="Left"
Content="{Binding}" Width="{Binding ControlWidth}" />
<Label Background="BlanchedAlmond" HorizontalAlignment="Left"
Content="{Binding}" Width="{Binding ElementName=Title, Converter={StaticResource NodeWidthConverter}}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</UserControl>
XmlUserControl codebehind
using System.Windows.Controls;
namespace WpfApplication
{
public partial class XmlUserControl : UserControl
{
public XmlUserControl()
{
InitializeComponent();
}
}
}
NodeWidthConverter
using System;
using System.Globalization;
using System.Windows.Data;
namespace WpfApplication2
{
public class NodeWidthConverter : IValueConverter
{
public static Random Random = new Random();
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return Random.Next(200, 600);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
Items.xml sample data
<Data>
<Items>
<Item Title="Title 1">
<Name>This is item name 1</Name>
<Summary>Summary for item 1</Summary>
</Item>
<Item Title="Title 2">
<Name>This is item name 2</Name>
<Summary>Summary for item 2</Summary>
</Item>
<Item Title="Title 3">
<Name>This is item name 3</Name>
<Summary>Summary for item 3</Summary>
</Item>
</Items>
</Data>
With this you'll get the following. Label has colored background to visualize the changing width properties.
Hope this helps!
So, you just need to bind SimpleControl.LabelWidth to PropertyView.LabelWidth? It can be achieved this way:
<W3V:SimpleControl
LabelWidth="{Binding Path=LabelWidth,
RelativeSource={RelativeSource AncestorType=PropertyView}}"
P.S. Your dependency property is registered as "LabelWidth2" (typo?). And new PropertyMetadata(0.0) is redundant, as default(double) == 0.0.
Do you have a failed binding back to your StaticResources? Do you have values defined in the resources section? Try something like this (note that I wrote this directly here (not in VS), it should be pretty much correct :)
<UserControl ...>
<UserControl.Resources>
<System.Int x:Key="ContentWidth">100</System.Int>
</UserControl.Resources>
<StackPanel Orientation="Horizontal" >
<TextBlock Width="{StaticResource LabelWidth}" Text="test"/>
<TextBox Width="{StaticResource ContentWidth}" />
</StackPanel>
</UserControl>
I would ask if you are really intending to go to StaticResources or whether you meant to bind to a property on a viewmodel or in the code behind of the view?

Binding Command on ContextMenuItem

I'm having trouble with binding a ContextMenuItem's command to my parent object. I've followed the following examples:
http://www.codeproject.com/Articles/162784/WPF-ContextMenu-Strikes-Again-DataContext-Not-Upda
RelativeSource binding from a ToolTip or ContextMenu
WPF: Binding a ContextMenu to an MVVM Command
And I've got a lot closer, but I still get the following error:
System.Windows.Data Error: 40 : BindingExpression path error: 'SearchString' property
not found on 'object' ''MainWindow' (Name='root')'.
BindingExpression:Path=Parent.PlacementTarget.Tag.SearchString; DataItem='MenuItem'
(Name=''); target element is 'MenuItem' (Name=''); target property is 'Command' (type
'ICommand')
The main window class has SearchString defined as:
public partial class MainWindow : Window
{
...
private void SearchString(object sender, RoutedEventArgs e)
{
throw new NotImplementedException();
}
}
but, obviously, the exception is never getting thrown.
I have the menu defined in a DataTemplate as follows:
<Window x:Class="CodeNaviWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:avalonEdit="http://icsharpcode.net/sharpdevelop/avalonedit"
Title="View" Height="865" Width="991"
x:Name="root"
>
<Window.Resources>
<DataTemplate x:Key="fileContentView">
<StackPanel>
<Border BorderThickness="3" BorderBrush="BurlyWood">
<avalonEdit:TextEditor
Width="400"
Height="400"
Document="{Binding Path=Document}"
IsReadOnly="True"
Tag="{Binding ElementName=root}">
<avalonEdit:TextEditor.ContextMenu>
<ContextMenu DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">
<MenuItem Header="Search..." Command="{Binding Path=Parent.PlacementTarget.Tag.SearchString, RelativeSource={RelativeSource Self}}" />
</ContextMenu>
</avalonEdit:TextEditor.ContextMenu>
</avalonEdit:TextEditor>
</Border>
</StackPanel>
</DataTemplate>
</Window.Resources>
...
</Window>
Can anyone see where I'm going wrong? If I change the method to be a string property then I don't get any errors, so I'm guessing that I'm somehow telling the XAML to expect a property, rather than a method.
Answering my own question here but hopefully this will prove useful for others. The solution that worked for me was to follow the answers given here: How do I add a custom routed command in WPF?
My MainWindow now looks like the following:
namespace MyNamespace
{
public partial class MainWindow : Window
{
public MainWindow()
{
...
}
...
private void SearchString(object sender, RoutedEventArgs e)
{
throw new NotImplementedException();
}
}
public static class Commands
{
public static readonly RoutedUICommand SearchString = new RoutedUICommand("Search String", "SearchString", typeof(MainWindow));
}
}
And the XAML has the following additions:
<Window x:Class="CodeNaviWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CodeNaviWPF"
xmlns:avalonEdit="http://icsharpcode.net/sharpdevelop/avalonedit"
Title="MyApp" Height="865" Width="991"
x:Name="root"
>
<Window.CommandBindings>
<CommandBinding Command="local:Commands.SearchString" Executed="SearchString" />
</Window.CommandBindings>
<Window.Resources>
<DataTemplate x:Key="fileContentView">
<StackPanel>
<Border BorderThickness="3" BorderBrush="BurlyWood">
<avalonEdit:TextEditor
Width="400"
Height="400"
Document="{Binding Path=Document}"
IsReadOnly="True"
Tag="{Binding ElementName=root}">
<avalonEdit:TextEditor.ContextMenu>
<ContextMenu DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">
<MenuItem Header="Search..." Command="local:Commands.SearchString" />
</ContextMenu>
</avalonEdit:TextEditor.ContextMenu>
</avalonEdit:TextEditor>
</Border>
</StackPanel>
</DataTemplate>
</Window.Resources>
...
</Window>

Why does my Custom UserControl's dependency property not work with dynamically binding?

My Custom UserControl's dependency property will bind correctly if the value is statically defined in the XAML calling it, like this:
TextBoxText="myName"
but not if the value is bound dynamically itself:
TextBoxText="{Binding ItemTypeIdCode}"
There is my full Code.
Custom UserControl XAML:
<UserControl
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"
x:Class="TestUserControl.UserControl1"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
x:Name="UserControl" Height="22" Width="282">
<Grid x:Name="LayoutRoot">
<TextBlock TextWrapping="Wrap" Text="{Binding MyName, ElementName=LayoutRoot}"/>
</Grid>
Custom UserControl Code:
public static readonly DependencyProperty TextBoxTextProperty =DependencyProperty.Register("TextBoxText", typeof(string), typeof(UserControl1));
public string TextBoxText
{
get { return (string)GetValue(TextBoxTextProperty); }
set { SetValue(TextBoxTextProperty, value); }
}
In my Main Window XAML :
<Grid x:Name="LayoutRoot">
<Button Content="Button" Height="78" Margin="0,0,93,112" VerticalAlignment="Bottom" HorizontalAlignment="Right" Width="94" Click="MyButtonClick"/>
<ListBox x:Name="MyListBox" HorizontalAlignment="Left" Margin="8,8,0,112" Width="192">
<ListBox.ItemTemplate>
<DataTemplate>
<local:UserControl1 HorizontalAlignment="Stretch" Margin="286,37,56,0" VerticalAlignment="Top" d:LayoutOverrides="Height" TextBoxText="{Binding MyName}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
In my Main Window Code :
private void MyButtonClick(object sender, System.Windows.RoutedEventArgs e)
{
List<string> MyName = new List<string>();
MyName.Add("Name 1");
MyName.Add("Name 2");
MyName.Add("Name 3");
MyListBox.ItemsSource = MyName;
}
This Code Successfully add my Custom UserControl as ListBoxItem in ListBox But Problem it is not display any text which i Binding.
I don`t understand where i am doing wrong.
You set the DataContext of the UserControl to itself, all bindings will then try to find the path on the UserControl, that is why you should not set the DataContext on UserControls.
You should see a binding error in the Output window of Visual Studio saying something like:
System.Windows.Data Error: 40 : BindingExpression path error: 'ItemTypeIdCode' property not found on 'object' ''UserControl1' (Name='UserControl')'. ...

Categories