小编Mas*_*aus的帖子

如何在使用箭头键行选择的焦点遍历中使DataGrid作为一个整体停止?

我有Window几个控件.其中一个是DataGrid.我想实现一些非默认的焦点遍历.即:

  • DataGrid 是一个整体,而不是每一行.
  • DataGrid聚焦时,用户可以使用向上和向下键导航行.
  • 不允许使用左右键导航列.
  • 第一列(和导航的唯一相关)是类型DataGridHyperlinkColumn.当用户点击Space或Enter键时,它会执行超链接.

目前我有以下代码:

<DataGrid x:Name="DocumentTemplatesGrid"
          Grid.Row="2"
          ItemsSource="{Binding Source={StaticResource DocumentTemplatesView}}"
          IsReadOnly="True"
          AutoGenerateColumns="False"
          SelectionUnit="FullRow"
          SelectionMode="Single"
          TabIndex="1"
          IsTabStop="True">
  <DataGrid.CellStyle>
    <Style TargetType="DataGridCell">
      <Setter Property="IsTabStop" Value="False"/>
    </Style>
  </DataGrid.CellStyle>
  <DataGrid.RowStyle>
    <Style TargetType="DataGridRow">
      <Setter Property="IsTabStop" Value="False"/>
    </Style>
  </DataGrid.RowStyle>
  <DataGrid.Columns>
    <DataGridHyperlinkColumn Header="Name"
                             Width="2*"
                             Binding="{Binding Name}"/>
    <DataGridTextColumn Header="Description"
                        Width="5*"
                        Binding="{Binding Description}"/>
    <DataGridTextColumn Header="Type"
                        Width="*"
                        Binding="{Binding Type}"/>
  </DataGrid.Columns>
</DataGrid>
Run Code Online (Sandbox Code Playgroud)

不幸的是,它没有达到我的期望.请你解释一下如何实现这个目标?

c# wpf datagrid focus tabstop

5
推荐指数
1
解决办法
270
查看次数

Task.Run和Task.Factory.StartNew有什么区别

我知道之前已经问过这个问题,但谷歌搜索后我得不到正确的答案.

我有这些代码行:

Task.Run(() => DoSomething())
    .ContinueWith(t=>Log.Error(t,"Error"), TaskContinuationOptions.OnlyOnFaulted);

Task.Factory.StartNew(() => DoSomething())
    .ContinueWith(t=>Log.Error(t,"Error"),TaskContinuationOptions.OnlyOnFaulted);
Run Code Online (Sandbox Code Playgroud)

成功运行后DoSomething,Task.Run投掷TaskCanceledExceptionTask.Factory.StartNew工作正常.为什么?

进一步阅读: Stephen Clearly为什么不使用Task.Factory.StartNew
MSDN Link

更新2: 示例代码:

private async void button27_Click(object sender, EventArgs e)
{
    var r = new Random(System.DateTime.Now.Millisecond);

    await Task.Factory.StartNew(
        () => {
            Divide(r.Next(100), r.Next(-1, 10));
            Log.Information("Divide Done!");
        },
        CancellationToken.None,
        TaskCreationOptions.DenyChildAttach,
        TaskScheduler.Default)
    .ContinueWith(
        t => {
            Log.Error(t.Exception,"There is an exception on Divide");
        },
        TaskContinuationOptions.OnlyOnFaulted);
}

private static void Divide(int a, int b)
{
    var c = a/b;
}
Run Code Online (Sandbox Code Playgroud)

c# multithreading task task-parallel-library c#-4.0

5
推荐指数
1
解决办法
2939
查看次数

在 ASP.NET MVC Core Web API 和 Entity Framework Core 中使用 TryUpdateModel 更新模型不起作用

我是 ASP.NET MVC Core Web API 和 EF Core 的新手,我正在创建一个简单的 MVC Web API 演示,如下所示。

[HttpPut("{id}")]
public async void Put(int id, [FromBody]Student student)
    {
        if (ModelState.IsValid)
        {
            var stu = _context.Students
                .Where(s => s.StudentId == id)
                .SingleOrDefault();

            var updateResult = await TryUpdateModelAsync<Student>(stu, "", s => s.FirstName, s => s.LastName, s => s.EnrollmentDate);
            _context.SaveChanges();
        }

    }
Run Code Online (Sandbox Code Playgroud)

问题是这TryUpdateModelAsync不起作用,更改没有更新到数据库。

我想知道:

  1. 如果TryUpdateModelAsync可以在MVC Web API 中使用?

  2. 我真的不想写像下面这样无聊的代码,如何避免从一个对象到另一个相同类型的对象进行属性值设置?(这是我使用的第一个原因TryUpdateModelAsync

    stu.FirstName = student.FirstName;
    stu.LastName = student.LastName;
    stu.SomeOtherProperties = student.SomeOtherProperties;
    _context.SaveChanges();
    
    Run Code Online (Sandbox Code Playgroud)

.NET 核心版本:1.1.0

ASP.Net …

entity-framework-core asp.net-core-mvc asp.net-core-webapi

5
推荐指数
1
解决办法
6041
查看次数

在 ASP.NET Core 中的每个操作之前查询数据库以获取角色授权

ASP.NET Core 结合 Identity 已经提供了一种在登录后检查角色的简单方法,但我想在每次控制器操作之前查询当前用户的当前角色的数据库。

我已经阅读了 Microsoft 提供的基于角色、基于策略和基于声明的授权。( https://docs.microsoft.com/en-us/aspnet/core/security/authorization/introduction ) 这些解决方案似乎都没有检查每个操作的角色。这是我以某种基于策略的授权的形式实现预期结果的最新尝试:

在 Startup.cs 中:

DatabaseContext context = new DatabaseContext();

services.AddAuthorization(options =>
{
    options.AddPolicy("IsManager",
        policy => policy.Requirements.Add(new IsManagerRequirement(context)));
    options.AddPolicy("IsAdmin",
        policy => policy.Requirements.Add(new IsAdminRequirement(context)));
});
Run Code Online (Sandbox Code Playgroud)

在我的需求文件中:

public class IsAdminRequirement : IAuthorizationRequirement
{
    public IsAdminRequirement(DatabaseContext context)
    {
        _context = context;
    }

    public DatabaseContext _context { get; set; }
}
public class IsAdminHandler : AuthorizationHandler<IsAdminRequirement>
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, IsAdminRequirement requirement)
    {
        // Enumerate all current users roles
        int userId = Int32.Parse(context.User.Claims.FirstOrDefault(c …
Run Code Online (Sandbox Code Playgroud)

c# authentication user-roles asp.net-core-mvc asp.net-core

5
推荐指数
1
解决办法
4124
查看次数

父类和子类之间的设计建议?

我正在进行物理模拟.

我有一个ArrayList包含模拟中所有对象的东西.我有一个父类:Shape和两个子类:CircleRectangle.

当然,父类没有draw()方法,但每个子类都有.因此,当我循环通过列表来绘制每个元素时,它不允许我,因为类中没有draw()方法Shape(因为我将列表定义为ArrayList<Shape>,并且每个新元素都添加一个子类)实例).

有没有办法以一种良好而整洁的方式解决这个问题?

java simulation class parent-child

5
推荐指数
1
解决办法
140
查看次数

使用C#(.Net Core)测量时间

我知道这个问题已经被问了不止一次,但是我不确定结果是否正确。该操作似乎太快了,所以我想仔细检查一下是否确实如此。

我有一个例程将一个字符串拆分为一个List<byte[]>。我想检查该操作所花费的时间,因此我将代码修改为如下所示:

// Deserializes base64 received from POST service
var str = JsonConvert.DeserializeObject<JsonText>(body).text;

Stopwatch stopWatch = Stopwatch.StartNew();

// parseText is a routine that splits str into
// byte[] of maximum size 100 and puts them into
// a List<byte[]> that is then returned 
commands = DummyClass.parseText(str);

stopWatch.Stop();
TimeSpan timespan = stopWatch.Elapsed;

Console.WriteLine(timespan.TotalMilliseconds.ToString("0.0###"));

...
Run Code Online (Sandbox Code Playgroud)

我使用8000个字符串运行了例程,预计运行时间为几毫秒,但令人惊讶的是,整个操作的运行时间最多为0.8ms,这预计会慢很多。

我读取的测量值有误吗?0.8表示8ms吗?在测量时间时我做错什么了吗?

非常感谢你!

c# .net-core

5
推荐指数
1
解决办法
5836
查看次数

WPF错误模板未显示

我没有绑定错误,此代码在另一个地方工作.我还没有发现我现在所做的与它工作的代码有什么不同,而且代码不是那么多.

UserControl.Resource中:

<Style TargetType="TextBox">
  <Setter Property="BorderBrush" Value="DarkBlue"/>
  <Setter Property="BorderThickness" Value="1"/>
  <Setter Property="Margin" Value="0,1,0,1"/>
  <Setter Property="Validation.ErrorTemplate">
    <Setter.Value>
      <ControlTemplate>
        <StackPanel Orientation="Horizontal">
          <AdornedElementPlaceholder/>
          <Grid Margin="2,0,0,0">
            <Ellipse Width="20" Height="20" Fill="Red"/>
            <TextBlock Foreground="White" Text="X" FontWeight="Bold"
                       HorizontalAlignment="Center" VerticalAlignment="Center"/>
          </Grid>
        </StackPanel>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
  <Style.Triggers>
    <Trigger Property="Validation.HasError" Value="True">
      <Setter Property="ToolTip"
              Value="{Binding RelativeSource={RelativeSource Self},
                  Path=(Validation.Errors)[0].ErrorContent}"/>
    </Trigger>
  </Style.Triggers>
</Style>
Run Code Online (Sandbox Code Playgroud)

下面也在Xaml中:

<TextBlock Height="23" HorizontalAlignment="Left" Margin="22,90,0,0"
           Text="Keywords" VerticalAlignment="Top"/>
<TextBox Height="23" HorizontalAlignment="Left" Margin="22,108,0,0"
         VerticalAlignment="Top" Width="244">
  <Binding Path="Tags" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
    <Binding.ValidationRules>
      <DataErrorValidationRule ValidatesOnTargetUpdated="False"/>
    </Binding.ValidationRules>
  </Binding>
</TextBox>
Run Code Online (Sandbox Code Playgroud)

我的ViewModel中的按钮SAVE仅在Model.Tags属性从用户输入10个字符时激活.当我输入10,11然后返回8个字符时,按钮激活/禁用工作正常.所有属性更改都会被触发.

型号:

namespace …
Run Code Online (Sandbox Code Playgroud)

wpf xaml templates mvvm idataerrorinfo

4
推荐指数
1
解决办法
4631
查看次数

DesignInstance在VS2013中不起作用

Visual Studio不显示具有DesignInstance属性的设计时数据.我已经检查DesignInstance过/没有MVVM Light.我花了很多时间来解决这个问题(也检查了StackOverflow上的类似问题),但DesignInstance根本不起作用.

项目:

  • SearchIdView.
  • SearchIdViewModel - 真实的视图模型.
  • DesignSearchIdViewModel- 继承SearchIdViewModel并包含设计时数据(属性在构造函数中分配).

环境:

  • VS2013 SP3
  • 净4.0
  • MvvmLight 5.0.2.0

SearchIdView.xaml

<Window x:Class="App1.View.SearchIdView"
    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:ignore="http://www.ignore.com"
    xmlns:design="clr-namespace:App1.Design"
    mc:Ignorable="d ignore"
    DataContext="{Binding SearchId, Source={StaticResource Locator}}"
    d:DataContext="{d:DesignInstance d:Type=design:DesignSearchIdViewModel,IsDesignTimeCreatable=True}"
    >
<Grid>
    <TextBlock Text="{Binding Test}" />
</Grid>
Run Code Online (Sandbox Code Playgroud)

SearchIdViewModel.cs

物业来自 SearchIdViewModel

public const string TestPropertyName = "Test";
private string _test;
public string Test
{
  get
  {
    return _test;
  }
  set
  {
    Set(TestPropertyName, ref _test, value);
  }
}
Run Code Online (Sandbox Code Playgroud)

你知道为什么DesignInstance在这种情况下不起作用吗? …

c# wpf mvvm mvvm-light

4
推荐指数
1
解决办法
1969
查看次数

AngularJS与ASP.NET MVC-Confused

请注意:我在Stack Overflow中已经阅读了类似的一些问题,但是没有从这些答案中得到我想要的清晰概念.

我清楚地了解为什么以及如何将AngularJS与ASP.NET Web API一起使用.但我对使用AngularJS和ASP.NET MVC感到困惑!

在使用ASP.NET Web API的AngularJS的情况下:

Web API控制器方法返回数据,AngularJS调用Web API控制器方法并捕获数据,然后在View中呈现数据.这非常符合逻辑!

在使用ASP.NET MVC的AngularJS的情况下:

ASP.NET MVC Controller方法本身返回带有数据的View/View.那么AngularJS与ASP.NET MVC有什么用?

尽管如此,如果我想在ASP.NET MVC中使用AngularJS,那么我必须从ASP.NET MVC控制器方法返回JSON而不是MVC视图.

我的问题是:

  1. 为了将AngularJS与ASP.NET MVC一起使用,从ASP.NET MVC控制器方法返回JSON而不是MVC视图是否合乎逻辑?如果我这样做,有什么好处吗?
  2. AngularJS与ASP.NET MVC的实际用途是什么?或者我在哪里可以将AngularJS与ASP.NET MVC一起使用?

c# asp.net asp.net-mvc asp.net-web-api angularjs

4
推荐指数
1
解决办法
1617
查看次数

如何在实体框架核心中重命名迁移

如何更改旧迁移的名称(重命名)?它与我的自定义身份用户的名称冲突。

更改身份用户会更容易吗?我也不知道如何重命名它,为了简单起见,每个教程都只是创建一个新的数据库(任何有关此的信息也值得赞赏)。

是否像将其重命名为一样简单:

  • 这是迁移 .cs 文件
  • 数据库迁移表
  • 快照

是这样吗?知道这会不会把事情搞砸吗?

entity-framework entity-framework-core

4
推荐指数
1
解决办法
2933
查看次数