I've made a simple project to illustrate my problem. I have a user control ('ButtonPod') that houses a button and a rectangle:
<UserControl x:Class="SilverlightDependencyProp.ButtonPod"
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"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<Rectangle Fill="Blue" />
<Button x:Name="ButtonOnPage" Margin="50" Content="Old button content" />
</Grid>
</UserControl>
I want to use this user control throughout my application, but I need to change the Button in the middle. I need control over all the properties of the Button, so I don't want to just expose DependencyProperties like 'ButtonText' or 'ButtonSize' - I would rather define the entire Button whenever I use the control. So I set up a dependency property ('CenterButton') like this:
public Button CenterButton
{
get { return (Button)GetValue(CenterButtonProperty); }
set { SetValue(CenterButtonProperty, value); }
}
public static readonly DependencyProperty CenterButtonProperty =
DependencyProperty.Register("CenterButton", typeof(Button),
typeof(ButtonPod), new PropertyMetadata(
CenterButtonChanged));
private static void CenterButtonChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var pod = d as ButtonPod;
pod.ButtonOnPage = e.NewValue as Button;
}
Then I try defining the 'CenterButton' on my MainPage.xaml, within my user control:
<Grid x:Name="LayoutRoot" Background="White">
<local:ButtonPod Width="200" Height="200">
<local:ButtonPod.CenterButton>
<Button Content="New button content" />
</local:ButtonPod.CenterButton>
</local:ButtonPod>
</Grid>
But when I load up the app, all I see is a button that says "Old button content" -- why isn't my button being replaced? Stepping through, I can see that the DependencyProperty gets hit and the 'ButtonOnPage' property gets set, but the visual tree does not update. Any ideas?
Setting a named element does not replace it. You want to name the parent and add the child to that instead (replacing the existing children).
Related
I was recently working on a user control, let's name it TestUserControl, and used two of its instances on one page.
While I was testing, I noticed, that when I type something into the values of upper TestUserControl, go to another page then go back to the first page - the second instance of TestUserControl is filled with values that had been typed into the first one (and even elements which are not part of user control of type TestUserControl are affected!).
Here are the screenshots of described behavior .
And the code of a simple project from which this screenshots come:
Landing page:
<Page x:Class="PageNavigation.Pages.Landing"
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:PageNavigation.Pages"
xmlns:controls="clr-namespace:PageNavigation.Controls"
xmlns:n="clr-namespace:PageNavigation"
mc:Ignorable="d"
d:DesignHeight="200"
d:DesignWidth="800"
Title="Landing">
<Grid Background="White"
ButtonBase.Click="Grid_Click">
<WrapPanel Margin="5">
<TextBlock Margin="0 25"
Text="I am a simple text block" />
<n:NavButton Text="Accounts"
ImageSource="/Images/Accounts.png"
NavUri="/Pages/Accounts.xaml" />
<n:NavButton Text="Bills"
ImageSource="/Images/Billing.png"
NavUri="/Pages/Bills.xaml" />
<n:NavButton Text="Employees"
ImageSource="/Images/Employees.png"
NavUri="/Pages/Employees.xaml" />
<n:NavButton Text="Setting"
ImageSource="/Images/Settings.png"
NavUri="/Pages/Setting.xaml" />
<StackPanel Orientation="Horizontal">
<TextBlock Text="User controls:" />
<controls:TestUserControl Width="150"/>
<controls:TestUserControl Width="150"/>
</StackPanel>
</WrapPanel>
</Grid>
</Page>
using System.Windows;
using System.Windows.Controls;
namespace PageNavigation.Pages
{
public partial class Landing : Page
{
public Landing()
{
InitializeComponent();
}
private void Grid_Click(object sender, RoutedEventArgs e)
{
if (e.OriginalSource is not NavButton ClickedButton)
return;
NavigationService.Navigate(ClickedButton.NavUri);
}
}
}
My testing user control:
<UserControl x:Class="PageNavigation.Controls.TestUserControl"
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:PageNavigation.Controls"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<StackPanel Margin="5">
<TextBox/>
<TextBox/>
<TextBox/>
<StackPanel Margin="10">
<ComboBox>
<ComboBoxItem>Item 1</ComboBoxItem>
<ComboBoxItem>Item 2</ComboBoxItem>
<ComboBoxItem>Item 3</ComboBoxItem>
</ComboBox>
</StackPanel>
<ToggleButton>Toggle me!</ToggleButton>
</StackPanel>
</UserControl>
using System.Windows.Controls;
namespace PageNavigation.Controls
{
public partial class TestUserControl : UserControl
{
public TestUserControl()
{
InitializeComponent();
}
}
}
Navigation button to another pages (these one with images):
using System;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
namespace PageNavigation
{
public class NavButton : ButtonBase
{
static NavButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(NavButton), new FrameworkPropertyMetadata(typeof(NavButton)));
}
public static readonly DependencyProperty ImageSourceProperty = DependencyProperty.Register("ImageSource", typeof(ImageSource), typeof(NavButton), new PropertyMetadata(null));
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(NavButton), new PropertyMetadata(null));
public static readonly DependencyProperty NavUriProperty = DependencyProperty.Register("NavUri", typeof(Uri), typeof(NavButton), new PropertyMetadata(null));
public ImageSource ImageSource
{
get { return (ImageSource)GetValue(ImageSourceProperty); }
set { SetValue(ImageSourceProperty, value); }
}
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public Uri NavUri
{
get { return (Uri)GetValue(NavUriProperty); }
set { SetValue(NavUriProperty, value); }
}
}
}
One of example pages which contains back button:
<Page x:Class="PageNavigation.Pages.Employees"
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:PageNavigation.Pages"
mc:Ignorable="d"
d:DesignHeight="450"
d:DesignWidth="800"
Title="Employees">
<Grid Background="White">
<Button Content="Back"
Padding="3"
Command="NavigationCommands.BrowseBack"
BorderThickness="0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Margin="5,5,0,0" />
<Label Content="Employees"
FontSize="50"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Grid>
</Page>
using System.Windows.Controls;
namespace PageNavigation.Pages
{
public partial class Employees : Page
{
public Employees()
{
InitializeComponent();
}
}
}
Main window:
<Window x:Class="PageNavigation.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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:PageNavigation"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Frame Source="/Pages/Landing.xaml" NavigationUIVisibility="Hidden"/>
</Grid>
</Window>
using System.Windows;
namespace PageNavigation
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
I'm using for the navigation System.Windows.Navigation.NavigationService and Frame, which seems to be important, as I couldn't reproduce this bug in a simple application that uses switching ContentControl and custom NavigationService.
When I use binding to view model in TestUserControl values, the problem seems to disappear, but what if I do not need binding, because I use elements of control to manage its internal behavior only - using for example toggle button to hide/show content of a text box field?
I was looking for an explanation for this behavior, but could not find any. I was reading about defining user controls, journal in Navigation Service, Data Context, and keeping alive pages when using Frames, but found nothing about user controls magically cloning their values to other controls.
I understand I could miss something simple or I defined all my user controls wrongly, but... this is not a behavior I would expect from a user control created in the simplest possible way.
I would appreciate it if someone could help me and answer my questions:
why is this happening? Is it a bug in WPF itself?
is this possible to create "safe" user control without necessarily using binding its values to an external source - and how to do it properly?
Sorry if I did not provide all the required information, but I don't know which information will be valuable as it seems to be a vague problem. I will try to answer any questions.
It's the frame journal which stores state for pages which have been shown.
If you don't go back to the previous page in your real app you could do:
NavigationService.RemoveBackEntry()
After you navigate.
That should remove whatever the journal just got.
You could also try giving things explicit X:Name and see if that allows the journal mechanism to differentiate.
Personally, I avoid frames and pages and I suggest you might consider using contentpresenter and usercontrols instead. I prefer viewmodel first navigation.
The discovered workaround is to bind values of controls to properties in code behind (it solves the problem) - at least visually.
My application is a topmost Window switching between multiple UserControl views. Its behavior is to close when the user clicks outside the window (more generally when it loses focus), and to show again when the user clicks on the system tray icon.
I'm having trouble getting the window to get focus when it shows up after clicking the tray icon. The problem is that the window shows up without focus and it doesn't hide when the user clicks outside. The user has to first click into the window and then click outside to trigger the Window's Deactivated event.
I can reproduce the problem with the most basic example from the documentation. I'm showing below the most basic representation of the problem I could produce.
I have tried many different things, none of which have shown any different behavior. For example, I tried calling the view's Focus() in the OnViewLoaded handler in the view models and deactivating the viewmodels instead of closing the window in the Close action. I also tried this suggestion on what seemed to be the same problem.
Any hint or help as to how to do this would be greatly appreciated.
[Export(typeof(ShellViewModel))]
public class ShellViewModel : Conductor<object>
{
IWindowManager windowManager;
[ImportingConstructor]
public ShellViewModel(IWindowManager windowManager)
{
this.windowManager = windowManager;
ShowPageOne();
}
public void ShowPageOne()
{
ActivateItem(new PageOneViewModel());
}
public void ShowPageTwo()
{
ActivateItem(new PageTwoViewModel());
}
public void Close()
{
this.TryClose();
// Using this to simulate the user clicking on a system tray icon
var timer = new Timer();
timer.Tick += (s, e) =>
{
windowManager.ShowWindow(this);
timer.Stop();
};
timer.Interval = 1000;
timer.Start();
}
}
My ShellView is:
<Window x:Class="PopupTest.ShellView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:tc="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit"
xmlns:cal="clr-namespace:Caliburn.Micro;assembly=Caliburn.Micro"
Width="300" Height="400"
cal:Message.Attach="[Event Deactivated] = [Action Close]"
Topmost="True">
<StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<Button x:Name="ShowPageOne" Content="Show Page One" />
<Button x:Name="ShowPageTwo" Content="Show Page Two" />
</StackPanel>
<ContentControl x:Name="ActiveItem" />
</StackPanel>
My two view models are:
public class PageOneViewModel : Caliburn.Micro.Screen { }
public class PageTwoViewModel : Caliburn.Micro.Screen { }
And the views are:
<UserControl x:Class="PopupTest.PageOneView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<TextBlock x:Name="bob" FontSize="32">Page One</TextBlock>
</UserControl>
I would like to know. How can I use dxb:Barbuttonitem together with caliburn micro.
I tried to write this code. But unfortunately it did not work.
<Window x:Class="WpfApplication1.ShellView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cal="http://www.caliburnproject.org"
xmlns:dxb="http://schemas.devexpress.com/winfx/2008/xaml/bars"
xmlns:dxr="http://schemas.devexpress.com/winfx/2008/xaml/ribbon"
Title="ShellView"
Width="300"
Height="300">
<Grid>
<dxb:BarManager Name="barManager1">
<dxb:BarManager.Items>
<dxb:BarButtonItem Name="Connect" Content="barButtonItem1" />
</dxb:BarManager.Items>
<DockPanel >
<dxr:RibbonControl DockPanel.Dock="Top">
<dxr:RibbonDefaultPageCategory Name="ribbonDefaultPageCategory1" Caption="defaultCategory">
<dxr:RibbonPage Caption="Home">
<dxr:RibbonPageGroup Name="ribbonPageGroup1" Caption="Tools">
<dxb:BarButtonItemLink BarItemName="Connect" />
</dxr:RibbonPageGroup>
</dxr:RibbonPage>
</dxr:RibbonDefaultPageCategory>
</dxr:RibbonControl>
<dxr:RibbonStatusBarControl DockPanel.Dock="Bottom" />
</DockPanel>
</dxb:BarManager>
</Grid>
[Export(typeof(IShell))]
public class ShellViewModel : PropertyChangedBase, IShell
{
public void Connect()
{
MessageBox.Show(string.Format("Hello {0}!", "aaa"));
}
public bool CanConnect()
{
return false;
}
}
If I use a standard button, all works fine.
This is not supported by CM since BarButtonItem inherits from FrameworkContentElement (CM supports messages on FrameworkElement only).
The CM forum post can be found here
There's a workaround for this problem that let's you trigger actions from DX's Bar items. You can use a static bar item and put any of standard controls (or buttons) inside then trigger actions from those elements. Example:
<dxb:BarStaticItem x:Name="LoadAllBarItem">
<dxb:BarStaticItem.ContentTemplate>
<DataTemplate>
<Button Content="Load all"
cal:Message.Attach="LoadAction"/>
</DataTemplate>
</dxb:BarStaticItem.ContentTemplate>
</dxb:BarStaticItem>
I have a WPF form, which consists of a grid of two columns.
In the left-hand column are the control labels, and in the right-hand column are my controls.
The controls are all UserControls. In the simplest case, some of these controls simply wrap existing WPF controls such as the textbox, so that they all implement a common interface.
When the form is generated, I have code like this to set the label for the associated control, where newControl is the created UserControl and ctl.Caption simply returns the required label text:
Label newLabel = new Label();
newLabel.Content = ctl.Caption + ":";
newLabel.Target = newControl;
One problem is that setting the Target doesn't actually work. If I have an underscore in the caption, the mnemonic key doesn't set focus to the wrapped control. One workaround for this may be to manually set the focus to the wrapped control within the UserControl code - but...
The biggest problem is accessibility. Screenreaders such as JAWS, and Windows built-in Narrator, do not read the control caption when the control receives focus.
I have had a look at this: http://msdn.microsoft.com/en-us/library/windows/desktop/gg712258.aspx - which provides a lot of detail, but no helpful examples. It has a lot of stuff about custom controls, which is surely overkill for a simple user control?
So, how can I "attach" my labels correctly to my UserControls?
You can browse the code for the entire project at http://quest.codeplex.com/SourceControl/changeset/view/676933506953 - the particular code is in the EditorControls project, and the UserControls are instantiated in ElementEditor.xaml.cs.
Your newControl is of type Control that doesn't allow you to add additional content.
If you want to add some content to it you need to use a class that supports it, like ContentControl or Panel (for multiple childs) you can implement you own control that implements the IAddChild interface.
A simple solution for you problem could be :
<UserControl x:Class="UIMocks.MyCustomControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel x:Name="content"/>
</UserControl>
The code-behind
[ContentProperty("Children")]
public partial class MyCustomControl : UserControl
{
public MyCustomControl()
{
InitializeComponent();
}
public UIElementCollection Children { get { return content.Children; } }
}
and then you can use
MyCustomControl newControl = InitialiseEditorControl(ctl);
...
Label newLabel = new Label();
newLabel.Content = ctl.Caption + ":";
newControl.Children.Add(newLabel);
hmmm I tried to reproduce your issue on a small test project, but for me it works... so I guess you'll have to give more details on how your userControls are built. Here is what works for me:
I created an Empty project (just the App and Window files, as usual) and set up a grid with 2 columns in my window:
<Window x:Class="Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Name="Window"
SizeToContent="WidthAndHeight">
<Grid Name="MyGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100" />
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
</Grid>
</Window>
then created a userControl that extends the wpf TextBox class:
<TextBox x:Class="Test.MyTextBox"
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">
</TextBox>
and:
using System.Windows;
using System.Windows.Controls;
namespace Test
{
public partial class MyTextBox : TextBox
{
public static readonly DependencyProperty CaptionProperty =
DependencyProperty.Register("Caption", typeof(string), typeof(MyTextBox), new UIPropertyMetadata(""));
public string Caption
{
get { return (string)GetValue(CaptionProperty); }
set { SetValue(CaptionProperty, value); }
}
public MyTextBox()
{
InitializeComponent();
}
}
}
it's basically a textbox with a "Caption" dp.
and now in My window's code behind:
public MainWindow()
{
InitializeComponent();
MyTextBox tb = new MyTextBox { Caption = "_Foo", Width = 100 };
Label lb = new Label { Content = tb.Caption + ":", Target = tb };
MyGrid.Children.Add(lb);
MyGrid.Children.Add(tb);
Grid.SetColumn(lb, 0);
Grid.SetColumn(tb, 1);
}
and with this, I do get focus on the TB when I press ALT + F (I can even see the _ under the F of "Foo" in the Label when just pressing ALT)
So I guess your issue has to do with your UserControls themselves and how they are built (what Template for instance)
Edit:
If your control is not extending an existing control but rather contains a WPF control, the issue is probably on the Focus method. You should add a Focus() method that sets the focus on the right part of your control when the control itself gets the focus.
code (for a UserControl containing a textbox that you want to get the focus for instance):
<TextBox x:Class="Test.MyTextBox"
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">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Button Content="foo" Grid.Column="0" />
<TextBox Name="TextBoxPart" Grid.Column="1" />
</Grid>
</TextBox>
code behind
public partial class MyTextBox : TextBox
{
public static readonly DependencyProperty CaptionProperty =
DependencyProperty.Register("Caption", typeof(string), typeof(MyTextBox), new UIPropertyMetadata(""));
public string Caption
{
get { return (string)GetValue(CaptionProperty); }
set { SetValue(CaptionProperty, value); }
}
public MyTextBox()
{
InitializeComponent();
}
protected override void OnGotFocus(RoutedEventArgs e)
{
TextBoxPart.Focus();
}
}
Edit 2:
I had an issue once, to transfer the focus to a subcontrol in a dataGridCell, and here is what I did in the template:
<ControlTemplate.Triggers>
<Trigger Property="IsFocused" Value="True">
<Setter TargetName="TextBoxPart" Property="FocusManager.FocusedElement" Value="{Binding ElementName=TextBoxPart}" />
</Trigger>
</ControlTemplate.Triggers>
you could try adding this to your template. This should transfer your focus alright.
as for the accessibility, I don't think this will help, but I do not see any way of achieving what you want :-/
I have this Custom UserControl which has a List and a Button:
<UserControl x:Class="WpfApplication1.CustomList"
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">
<Grid>
<ListBox Name="listBox1" ItemsSource="{Binding ListSource}" HorizontalAlignment="Right" Width="174" />
<Button Name="ButtonAdd" Content="Add" HorizontalAlignment="Left" Width="101" />
</Grid>
</UserControl>
The code behind has a DependencyProperty of Type IEnumerable and a handler(OnAdd) for the Button:
public partial class CustomList : UserControl
{
public CustomList( )
{
InitializeComponent( );
ButtonAdd.Click += new RoutedEventHandler( OnAdd );
}
private void OnAdd( object sender, EventArgs e )
{
IList<object> tmpList = this.ListSource.ToList( );
Article tmpArticle = new Article( );
tmpArticle .Name = "g";
tmpList.Add(tmpArticle );
ListSource = (IEnumerable<object>) tmpList;
}
public IEnumerable<object> ListSource
{
get
{
return (IEnumerable<object>)GetValue( ListSourceProperty );
}
set
{
base.SetValue(CustomList.ListSourceProperty, value);
}
}
public static DependencyProperty ListSourceProperty = DependencyProperty.Register(
"ListSource",
typeof( IEnumerable<object> ),
typeof( CustomList ),
new PropertyMetadata( OnValueChanged ) );
private static void OnValueChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
{
( (CustomList)d ).ListSource = (IEnumerable<object>)e.NewValue;
}
}
In the Button handler I am trying to add an Article to the ListSource(which is bound to the Articles).
This is the window where I use my UserControl(CustomList):
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:local="clr-namespace:WpfApplication1"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Title="MainWindow" Height="350" Width="525">
<Grid>
<local:CustomList ListSource="{Binding Articles, Mode=TwoWay}" Margin="80,0,0,0" />
</Grid>
</Window>
When I click the Button, the Articles become null instead of adding an Article in the in the Articles collection. And the ListSource property also becomes null. Am I doing something wrong here? Is this an expected behavior? If yes, what would be a different way of doing this:
Create a Custom Control that will have a List and a Button and the handler for the button will add objects in the List.
There are a lot of issues here but the main one that's causing your problem is that there is probably a type mismatch between the properties that you are trying to use TwoWay Binding on. You didn't list the code for your Articles property, but I assume it's probably something like IEnumerable<Article> or ObservableCollection<Article> and not IEnumerable<object> as is your ListSource property.
When you set up two way Binding and the target value can't be converted back to the source type (i.e. IEnumerable<object> -> ObservableCollection<Article>) the source property (Articles here) will receive a null value, which will then get pushed back through the Binding to the target property (ListSource here).
You can change the type on either side but if you're using them with a TwoWay Binding the types should match.
In general it's a bad idea to use TwoWay Bindings with collections. Instead of copying and replacing the collection instance every time you want to make a change, just add and remove items from one instance. Since that one instance is the same collection on both sides of the (OneWay) Binding the updates will show up on both sides, and if you're using an ObservableCollection you can also get change notifications on either side.
You should also get rid of your OnValueChanged code since it is just resetting the property to the value that was just set on the property.