hey guys i created an wpf application with custom usercontrol , the problem is that i am unable to update or say change the properties of custom control at runtime,
–>heres a code of user control
File:usercontrol.xaml
<UserControl x:Class="ExampleWpf.UserControlExample"
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"
Width="Auto" Height="Auto">
<Rectangle Width="60" Height="200" Fill="#FFB65959" Name="Box1"></Rectangle>
File:usercontrol.xaml.cs
namespace ExampleWpf{
public partial class UserControlExample : UserControl
{
public UserControlExample()
{
InitializeComponent();
}
public double Box1Width
{
get { return (Box1.Width); }
set { Box1.Width = value; }
}
}
—>Heres a simple code for Wpfapplication
File:Mainwindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
UserControlExample uc = new UserControlExample();
uc.Box1Width = 100;
}
}
All i wanted to change the width of a custom control at run time when user click on the button—-> but unfortunately i doesn’t succeed
please help me out
You are creating a new instance of your user control and not doing anything with it.
You should be finding the existing instance of the control and updating that.
You should also implement this type of behaviour through Dependency Properites. This gives you all sorts of advantages as outlined in the tutorial, but the main one here is that you can set properties like this at runtime.