如何在 WinUI 3 桌面應用程式中使用 ObservableObject(來自 Community Toolkit)作為代碼中的系結目標和 XAML?
這是一個簡單的(部分)主頁示例:
<!-- Home.xaml -->
<Page
x:Class="PFSI.Views.Home"
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:vms="using:PFSI.ViewModels"
mc:Ignorable="d" >
<Page.DataContext>
<vms:HomeViewModel x:Name="ViewModel" />
</Page.DataContext>
<Grid x:Name="ContentArea" >
<TextBlock x:Name="TBox" Text="This text should be shaded." Foreground="{Binding Shade}" />
</Grid>
</Page>
// Home.xaml.cs
public partial class HomePage : Page
{
public HomePage()
{
InitializeComponent();
}
}
// HomeViewModel.cs
public class HomeViewModel : ObservableObject
{
public HomeViewModel()
{
Classes.TraceListener.TraceMessage(GetType().Name);
}
[ObservableProperty]
private SolidColorBrush shade;
}
在 XAML(請參閱 Home.xaml 中的 TextBlock)或代碼中使用屬性 Shade 作為源很簡單:
Binding bBinding = new() { Path = new PropertyPath("Shade"), Source = ViewModel, Mode = BindingMode.OneWay };
TBox.SetBinding(TextBox.ForegroundProperty, bBinding);
但是如果我想讓屬性 Shade 成為系結的目標(即我想用系結設定 Shade)呢?
BindingOperations.SetBinding(DependencyObject target, DependencyProperty dp, BindingBase binding)需要一個 DependencyObject(HomeViewModel 不是,它是一個 ObservableObject)和一個 DependencyProperty 識別符號(Shade 沒有,因為它是一個普通屬性)。
我確信這是可能的,但我現在不知所措。歡迎任何幫助。
uj5u.com熱心網友回復:
如何在 WinUI 3 桌面應用程式中使用 ObservableObject(來自 Community Toolkit)作為代碼中的系結目標和 XAML?
你不能因為系結的目標屬性必須是依賴屬性。
我確信這是可能的......
并非沒有將目標屬性轉換為依賴屬性(并將類轉換為 a DependencyObject)。
我不明白為什么你需要同時擴展ObservableObject兩者DependencyObject。它是一個或另一個,即你的類是某種視圖模型或某種控制。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/504923.html
標籤:C# 捆绑 winui-3 Windows 社区工具包 可观察对象
