프로그래밍/WPF
[WPF] UserControl DependencyProperty 설정과 Binding 방법
흔한티벳여우
2021. 7. 21. 13:31
반응형
자주 쓰이는 UserControl을 만들 때, 해당 컨트롤을 바딩인 속성 설정과 실제 바인딩 방법에 대해 알아본다.
Usercontrol xaml
<UserControl x:Class="WintexMonitoring.View.MaterialCard"
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:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
xmlns:local="clr-namespace:WintexMonitoring.View"
mc:Ignorable="d"
>
<Grid>
<TextBlock Text="{Binding Title, RelativeSource={RelativeSource AncestorType=local:MaterialCard}}"/>
</Grid>
</UserControl>
cs
namespace WintexMonitoring.View
{
/// <summary>
/// MaterialCard.xaml에 대한 상호 작용 논리
/// </summary>
public partial class MaterialCard : UserControl
{
public string Title
{
get { return (string)GetValue(TitleValueProperty); }
set { SetValue(TitleValueProperty, value); }
}
public static readonly DependencyProperty TitleValueProperty =
DependencyProperty.Register("Title", typeof(string), typeof(MaterialCard), new PropertyMetadata(string.Empty));
public MaterialCard()
{
InitializeComponent();
}
}
}
Usercontrol 을 사용하는 곳은 일반적인 방법으로 viewModel로 바인딩하면된다.
<Page x:Class="WintexMonitoring.View.DashboardView"
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:WintexMonitoring.View"
xmlns:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
xmlns:vm="clr-namespace:WintexMonitoring.ViewModel"
xmlns:uc="clr-namespace:WintexMonitoring.View"
mc:Ignorable="d"
Title="DashboardView"
>
<Grid>
<StackPanel Orientation="Horizontal">
<uc:MaterialCard Title="{Binding Path=Machine1}" Margin="10"/>
</StackPanel>
</Grid>
</Page>
반응형