Note that there are some explanatory texts on larger screens.

plurals
  1. POWPF How to expose fields on a UserControl
    primarykey
    data
    text
    <p>I have a simple application with just a window and a user control. The user control has a list box. The user control is positioned on the Window and I want to bind the user control's listbox to an element on the window's data context. </p> <p>The examples I've been able to find have CLR properties on the user control which are accessed in code not via XAML. </p> <pre><code>&lt;Window x:Class="WpfApplication2b.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:WpfApplication2b="clr-namespace:WpfApplication2b" Title="MainWindow" Height="410" Width="520"&gt; &lt;Grid&gt; &lt;WpfApplication2b:MyUserControl&gt;&lt;/WpfApplication2b:MyUserControl&gt; &lt;/Grid&gt; </code></pre> <p></p> <p>And here is the user control itself.</p> <pre><code>&lt;UserControl x:Class="WpfApplication2b.MyUserControl" 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" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"&gt; &lt;Grid Background="#FFD8AA13"&gt; &lt;ListBox Height="276" HorizontalAlignment="Left" Margin="12,12,0,0" Name="listBox1" VerticalAlignment="Top" Width="276" /&gt; &lt;/Grid&gt; </code></pre> <p></p> <p>As you can see it's just a listbox on a different coloured background. I have no idea where to go next :)</p> <p>I'm guessing that I need to add a code behind property for the list box as a dependency property?</p> <p>Edit: I've added a dependencyProperty, but I don't think I've quite got the point.</p> <pre><code> public partial class MyUserControl : UserControl { public static readonly DependencyProperty ListBoxProperty; static MyUserControl() { FrameworkPropertyMetadata md = new FrameworkPropertyMetadata(); MyUserControl.ListBoxProperty = DependencyProperty.Register("MyListBox", typeof (ListBox), typeof (MyUserControl), md); } public ListBox MyListBox { get { return (ListBox) GetValue(ListBoxProperty); } set { SetValue(ListBoxProperty, value); } } public MyUserControl() { InitializeComponent(); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload