实际上,根据标题,当基类是通用的时,如何在XAML中设置依赖属性?当我尝试这样做时,我得到一个NullReferenceException,从后面的代码设置属性工作正常.它也适用于基类不通用的情况.我正在使用.NET4
以下是一些示例代码:
WindowBase.cs
using System.Windows;
namespace GenericDependencyPropertyTest
{
public class WindowBase<ViewModel> : Window
{
public static readonly DependencyProperty HeaderProperty = DependencyProperty.Register(
"Header", typeof(string), typeof(WindowBase<ViewModel>), new PropertyMetadata("No Header Name Assigned"));
public string Header
{
get { return (string)GetValue(HeaderProperty); }
protected set { SetValue(HeaderProperty, value); }
}
protected virtual ViewModel Model { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
MainWindow.xaml
<local:WindowBase x:Class="GenericDependencyPropertyTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:GenericDependencyPropertyTest"
x:TypeArguments="local:IMyViewModel"
Title="MainWindow" Height="350" Width="525" Header="Test">
<Grid>
</Grid>
</local:WindowBase>
Run Code Online (Sandbox Code Playgroud)
MainWindow.xaml.cs
namespace GenericDependencyPropertyTest
{
/// <summary>
/// Interaction logic for MainWindow.xaml …Run Code Online (Sandbox Code Playgroud) 我正在尝试设置Google Play等标签,我正在按照本指南转换为C#,但在调用时会抛出异常tabLayout.SetupWithViewPager.活动的代码是这样的:
public class MainActivity : FragmentActivity
{
protected override void OnCreate(Bundle bundle) {
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
var viewPager = FindViewById<ViewPager>(Resource.Id.viewpager);
viewPager.Adapter = new SampleFragmentPagerAdapter(SupportFragmentManager, this);
var tabLayout = FindViewById<TabLayout>(Resource.Id.sliding_tabs);
tabLayout.SetupWithViewPager(viewPager);
}
}
Run Code Online (Sandbox Code Playgroud)
异常的堆栈跟踪是:
07-28 23:08:39.068 I/MonoDroid( 4040): UNHANDLED EXCEPTION:
07-28 23:08:39.071 I/MonoDroid( 4040): Android.Views.InflateException: Exception of type 'Android.Views.InflateException' was thrown.
07-28 23:08:39.071 I/MonoDroid( 4040): at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () <IL 0x00011, 0x0004b>
07-28 23:08:39.071 I/MonoDroid( 4040): at Android.Runtime.JNIEnv.CallVoidMethod (intptr,intptr,Android.Runtime.JValue*) [0x00063] in /Users/builder/data/lanes/1879/5f55a9ef/source/monodroid/src/Mono.Android/src/Runtime/JNIEnv.g.cs:571
07-28 23:08:39.071 I/MonoDroid( 4040): at Android.Support.Design.Widget.TabLayout.SetupWithViewPager …Run Code Online (Sandbox Code Playgroud)