這裏是我的用戶XAML用戶控件不工作
<UserControl x:Class="UserControlTest.Controls.FullNameControl"
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:local="using:UserControlTest.Controls"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
d:DesignHeight="100"
d:DesignWidth="100"
mc:Ignorable="d">
<Grid>
<TextBlock Text="{Binding FirstNameText}" />
</Grid>
</UserControl>
這裏是代碼後面的用戶控件
public sealed partial class FullNameControl : UserControl
{
public FullNameControl()
{
this.InitializeComponent();
}
public string FirstNameText
{
get { return (string)GetValue(FirstNameTextProperty); }
set { SetValue(FirstNameTextProperty, value); }
}
public static readonly DependencyProperty FirstNameTextProperty =
DependencyProperty.Register("FirstNameText", typeof(string),
typeof(FullNameControl), new PropertyMetadata(String.Empty));
}
下面是一個使用用戶控件
<Page x:Class="UserControlTest.Views.PageWithUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Behaviors="using:Template10.Behaviors"
xmlns:Core="using:Microsoft.Xaml.Interactions.Core"
xmlns:Interactivity="using:Microsoft.Xaml.Interactivity"
xmlns:controls="using:Template10.Controls"
xmlns:uControls="using:UserControlTest.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="using:UserControlTest.Views"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="using:UserControlTest.ViewModels"
mc:Ignorable="d">
<Page.DataContext>
<vm:PageWithUserControlViewModel x:Name="ViewModel" />
</Page.DataContext>
<Grid>
<uControls:FullNameControl FirstNameText="{Binding FirstName, Mode=OneWay}" />
</Grid>
</Page>
這裏是頁填充視圖的視圖模型。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Template10.Common;
using Template10.Mvvm;
using Template10.Services.NavigationService;
using Windows.UI.Xaml.Navigation;
namespace UserControlTest.ViewModels
{
public class PageWithUserControlViewModel : ViewModelBase
{
public PageWithUserControlViewModel()
{
}
private string _FirstName = "Default";
public string FirstName { get { return _FirstName; } set { Set(ref _FirstName, value); } }
public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> suspensionState)
{
FirstName = "Terrence";
await Task.CompletedTask;
}
public override async Task OnNavigatedFromAsync(IDictionary<string, object> suspensionState, bool suspending)
{
await Task.CompletedTask;
}
public override async Task OnNavigatingFromAsync(NavigatingEventArgs args)
{
args.Cancel = false;
await Task.CompletedTask;
}
}
}
你怎麼看「用戶控件不工作」的含義之後,用戶控制的構造? –
數據未從視圖模型填充。因此,使用該usercontrol的所有頁面都不會顯示usercontrol中這些字段的任何數據。 – Terrence